Model item bind in List

时间:2019-01-15 18:23:02

标签: c# jquery asp.net-mvc model

I have passed the model to partial view,And then i need to bind some text fields to the model in the view.

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

}

Model

 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();
}

1 个答案:

答案 0 :(得分:1)

You want to use a traditional for loop so you can use the index to bind to your List<T> in the model, you'll also need to make items mutable, so you'll need to have a set for it as well or else you won't be able to submit anything:

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

Then in your View:

@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>
}