如何绑定带有asp-for标签的数组? [英] How can I bind an array with asp-for tag?

查看:460
本文介绍了如何绑定带有asp-for标签的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下,如何在Asp.NET Core MVC中绑定数组?

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

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

在旧版本的ASP MVC中,它运行得很好. 此示例显示内部服务器错误".

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

"在编译处理该请求所需的资源期间发生错误.请查看以下特定的错误详细信息,并适当地修改您的源代码."

ViewModel类示例:

ViewModel class example:

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

模型类示例:

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

它应该如何工作?使用这些输入提交表单后,MVC应该自动在ModelView中创建和映射列表.这就是它在ASP.NET MVC 4中的工作方式.

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.

推荐答案

您需要使用带有asp-for且可以编译的有效表达式,基本上,如果index是您在for循环中使用的变量,则您会写<input asp-for="@Model.Requests[index].Name" />

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" />

完整示例(我将i用作循环变量而不是index):

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>

有关更多信息,请在 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆