Reputation: 153
I've seen a few very similar posts on here regarding iterating through a list of models and creating a form within each iteration, but nothing has led me to successfully POST back a populated model.
My goal is to present an inline form for each iteration of the model and allow users to make changes and save the edits for that specific model when the associated form gets submitted. I'm still fairly new to ASP.NET MVC so if there is a better way to go about this, please feel free to offer suggestions.
Thanks in advance for any help with this!
View
@model List<POSGuys.Option>
@{
var options = Model.OrderBy(i => i.OptionEndOfLife).ToList();
}
@for (int i = 0; i < options.Count(); i++)
{
using (Html.BeginForm("Save", "Option", FormMethod.Post ))
{
<tr style="@(options[i].OptionEndOfLife ? "color:#777" : "")">
@Html.HiddenFor(model => options[i].OptionID)
<td>@options[i].ItemNumber</td>
<td width="100"><img @Html.Raw(POSGuys.Controllers.Shims.Resize("/content/images/catalog/" + options[i].image, 200, 200, rescale: 2)) /></td>
<td>@Html.EditorFor(model => options[i].OptionName)</td>
<td>@Html.EditorFor(model => options[i].PGPrice)</td>
<td>@Html.EditorFor(model => options[i].OptionsMSRP)</td>
<td>@Html.EditorFor(model => options[i].Cost)</td>
<td>@Html.EditorFor(model => options[i].Description)</td>
<td>@Html.EditorFor(model => options[i].Rank)</td>
<td>@Html.EditorFor(model => options[i].Standard)</td>
<td><input type="submit" value="Save" class="btn btn-warning" /></td>
</tr>
}
}
Controller
[HttpPost]
public ActionResult Save(Option option)
{
var opt = StoreDatabase.Options.Find(option.OptionID);
if (opt != null)
{
StoreDatabase.Entry(opt).CurrentValues.SetValues(option);
StoreDatabase.SaveChanges();
}
return RedirectToAction("EditList", option.ProductID);
}
Upvotes: 1
Views: 3410
Reputation: 383
Much easier solution - create partial view. If you have your main view as List your partial should be just Model and everything will work like it should.
Upvotes: 1
Reputation: 218892
You just need to make sure that your code is generating the input field's with name values same as the property names of the Option class and model binding will work.
@for (int i = 0; i < options.Count(); i++)
{
using (Html.BeginForm("Save", "Option", FormMethod.Post))
{
@Html.EditorFor(model => options[i].OptionName,null,"OptionName")
@Html.EditorFor(model => options[i].PGPrice,null, "PGPrice")
<input type="submit" />
<br />
}
}
Now when you submit the form, the Default model binder will be able to map the form field values to the properties of the Option class object.
Upvotes: 5