Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind an array with asp-for tag?

I would like to ask, how can I bind an array in Asp.NET Core MVC ?

<input type="text" asp-for="Requests[@index].Name" />

It was working very well in older versions of ASP MVC. This example shows "Internal server error".

"An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately."

ViewModel class example:

public class ViewModel
{
    public List<Model> Requests {get;set;}
}

Model class example:

public class Model
{
    public string Name {get;set;}
}

How it should work ? After you submit a form with these inputs, MVC should automaticly create and map the list in ModelView. That's how It works in ASP.NET MVC 4.

like image 614
wh1sp3r Avatar asked Jan 26 '17 12:01

wh1sp3r


People also ask

What is asp for tag?

asp-for sets the id , name and validation related attributes, and it also sets the value of the input element if there is already a value within the model passed to the view – if that's what you are asking.

Which tag helper is used to perform model binding?

The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.

What is bind asp net?

The model binding system: Retrieves data from various sources such as route data, form fields, and query strings. Provides the data to controllers and Razor pages in method parameters and public properties. Converts string data to . NET types.

Which is the correct syntax of tag helper in form tag?

The syntax to register all the tag helpers that are in an assembly is to use asterisk comma (*,) and then the assembly name, Microsoft. AspNet. Mvc. TagHelpers.


1 Answers

You need to use a valid expression with asp-for that can be compiled, basically if index is a variable you are using in a for loop then you would write <input asp-for="@Model.Requests[index].Name" />

Full example (I've used i as the loop variable instead of index):

@model MyProject.TodoItemList

<ul>
@for (int i = 0; i < Model.Requests.Count; i++)
{
    <li>                
        <label asp-for="@Model.Requests[i].Name"></label>
        <input asp-for="@Model.Requests[i].Name"/>
        @* Or the old html helpers if you prefer
           @Html.DisplayFor(model => model.Requests[i].Name)
        *@                
    </li>
}
</ul>

For more info, check Expression names and Collections in the docs

like image 109
Daniel J.G. Avatar answered Oct 07 '22 17:10

Daniel J.G.