首页 > 解决方案 > List 中的模型项绑定

问题描述

我已经将模型传递给局部视图,然后我需要将一些文本字段绑定到视图中的模型。

@model SRINews.Domain.NewsTotal

@using (Html.BeginForm("UpdateNewsItem", "Home", FormMethod.Post))
{
    <table class="table table-borderless table-cart" id="mytable" data-addclass-on-smdown="table-sm">
        <tbody>
            @foreach (var item in Model.items)
            {
                <tr class="newsRow" id="@item.ItemId">
                    <td class="cart-img nostretch">
                        <a href="#"><img src="@item.ImageUrl" alt=""></a>
                    </td>
                    </tr>
                    <tr>
                    <td>
                     <input type="text" class="form-control" placeholder="Personalized Name">
                     //@Html.TextboxFor(x=>x)
                     // I want to bind PersonalizedName to model
                    </td>
                    </tr>
                    <tr>
                    <td>
                     <input type="text" class="form-control" placeholder="Country">
                      // I want to bind Country to model
                    </td>
                    </tr>
                    }
                    </tbody>
                    </table>

                       <input type="submit" class="btn btn-primary" value="Personal Details" />

}

模型

 public class Items
    {
        public int ItemId { get; set; }
        public string ItemCode { get; set; }
        public string PersonalizedName {get;set;}
        public string Country {get;set;}
    }

    public class NewsTotal
    {
        public int BaseItem { get; set; }
        public string BaseName {get;set;}
        public List<Items> items { get; } = new List<Items>();
    }

Public ActionResult UpdateNewsItem(NewsTotal nTotal)
{
return View();
}

标签: c#jqueryasp.net-mvcmodel

解决方案


您想使用传统的 for 循环,因此您可以使用索引绑定到List<T>模型中的您,您还需要使其items可变,因此您还需要有一个setfor 它,否则您将不会能够提交任何东西:

//You'll need to make this mutable, so it can post the edited values
public List<Items> items { get; set; } = new List<Items>();

然后在您的视图中:

@for(int i = 0; i < Model.items.Count; i++)
{
   @Html.HiddenFor(x => Model.items[i].ItemId)
   @Html.HiddenFor(x => Model.items[i].ItemCode)
   <tr class="shoppingCartRow" id="@Model.items[i].ItemId">
     <td class="cart-img nostretch">
       <a href="#"><img src="@Model.items[i].ImageUrl" alt=""></a>
     </td>
   </tr>
   <tr>
     <td>
       @Html.TextboxFor(x=> Model.items[i].PersonalizedName, new { @placeholder = "Personalized Name"})
     </td>
   </tr>
   <tr>
     <td>
       @Html.TextboxFor(x=> Model.items[i].Country, new { @placeholder = "Country"})
     </td>
   </tr>
}

推荐阅读