簡體   English   中英

如何使用 asp-for 標記綁定數組?

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

請問,如何在Asp.NET Core MVC 中綁定數組?

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

它在舊版本的 ASP MVC 中運行良好。 此示例顯示“內部服務器錯誤”。

"在編譯處理此請求所需的資源期間發生錯誤。請查看以下特定錯誤詳細信息並適當修改您的源代碼。 "

ViewModel 類示例:

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

模型類示例:

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

它應該如何工作? 在您提交帶有這些輸入的表單后,MVC 應該自動創建並映射 ModelView 中的列表。 這就是它在 ASP.NET MVC 4 中的工作方式。

您需要使用可以編譯的asp-for的有效表達式,基本上如果index是您在 for 循環中使用的變量,那么您將編寫<input asp-for="@Model.Requests[index].Name" />

完整示例(我使用i作為循環變量而不是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>

有關更多信息,請查看文檔中的表達式名稱和集合

如果要使用單獨的局部視圖綁定列表:

首先,創建返回列表的操作。

public async Task<ActionResult> UpdateTable([FromForm]Filter filter)
{
    if (ModelState.IsValid)
    {           
        List<Model> model = new List<Model>();
        ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("Requests");
        return PartialView("_PartialViewOfModel", model);
    }
    return BadRequest(ModelState);
}

這段代碼將出現在您的部分視圖中。

@model List<Model>
@for (int i = 0; i < Model.Count; i++)
{
    <input type="text" class="form-control form-control-sm" asp-for="@Model[i].Name" />
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM