0

I have a ProductViewModel in which Each Product has Multiple Images,Bullet_Points.I am Able to Display the Data to Edit Function However have little logic in catching the data back to POST Edit Method.

@model OMS.ViewModels.ProductVm2
@using(Html.BeginForm()) {
  @Html.AntiForgeryToken() < h4 > ProductVM < /h4> < hr / >
   < div class = "form-horizontal" >


  @Html.HiddenFor(m => m.Product.ProductID)


       @foreach (var img in Model.Images)
    {
    <div class="form-group">
       @Html.LabelFor(modelItem => img.Image_URL, htmlAttributes: new { @class = "control-label col-md-2" })
       <div class="col-md-10">
          @Html.EditorFor(modelItem => img.Image_URL, new { htmlAttributes = new { @class = "form-control" } })
          @Html.ValidationMessageFor(@modelItem => img.Image_URL, "", new { @class = "text-danger" })
       </div>
    </div>
    }

How Should i Catch the Collection of Images into Controllers [HTTPPOST] Edit Method.Because the Method Should Iterate over Images Model . I am able to Catch other model data with no Issues.

public ActionResult Edit(FormCollection form, ProductVm2 VM) {

    Product product = new Product() { //Supplier_ID = VM.Product.Supplier_ID, 
     Name = VM.Product.Name, Description = VM.Product.Description, Product_Code = VM.Product.Product_Code,
      ProductID = VM.Product.ProductID
    };

//Images
List<Image> Images = new List<Image>();

 Images.Add( ......)

}

Also While i was trying to check the objects that were sent from View to Controller.I see that Image object is null even when i have passed data into it.

enter image description here

Arun3x3
  • 193
  • 1
  • 7
  • 17

1 Answers1

0

You cannot really use the foreach and have this work, the default model binder wants collection index syntax to create the bind-able element ids correctly.....

instead of

@foreach (var img in Model.Images)
{
<div class="form-group">
   @Html.LabelFor(modelItem => img.Image_URL, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
      @Html.EditorFor(modelItem => img.Image_URL, new { htmlAttributes = new { @class = "form-control" } })
      @Html.ValidationMessageFor(@modelItem => img.Image_URL, "", new { @class = "text-danger" })
   </div>
</div>
}

Use this

@for (int i = 0; i < Model.Images.Count(); i++)
{
<div class="form-group">
   @Html.LabelFor(x=> x.Images[i].Image_URL, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
      @Html.EditorFor(x=> x.Images[i].Image_URL, new { htmlAttributes = new { @class = "form-control" } })
      @Html.ValidationMessageFor(x => x.Image[i].Image_URL, "", new { @class = "text-danger" })
   </div>
</div>
}
Paul Swetz
  • 2,234
  • 1
  • 11
  • 28