Reputation: 5029
I've been having trouble figuring out how to edit table items on a webpage, and post them back to the server. (actually, in this case, I just want the user to select checkboxes, as though they are selecting multiple items, but that's just the implimentation).
The problem is that, while the view shows up on the webpage, in HttpPost, picSelections is null.
This is at the top of my View:
@model IEnumerable<CarShow.lmit_pics>
@using (Html.BeginForm())
{
<div style="width:100%; height:60px; ">
<input type="submit" value="Add Selected Photo(s) to Survey" />
</div>
for (int i = 0; i < Model.Count(); i++)
{
var item = Model.ElementAt(i);
<div style="width:296px; float:left">
<div style="float:left; width:200px; margin-bottom:18px">
@{string cropped = "../../../Content/Images/" + Html.DisplayFor(modelItem => item.picname).ToString() + "?" + Html.DisplayFor(modelItem => item.version).ToString();
}
<img alt="picture" class="pic-size" src="@cropped" />
<br />
@Html.EditorFor(modelItem => item.brand)
</div>
</div>
}
}
</div>
This is in the controller:
public ActionResult AddSurveyPic(string id)
{
var validPicSummaries = (IEnumerable)(from x in db.lmit_pics where x.enabled == 1 select x);
return View((IEnumerable)validPicSummaries);
}
[HttpPost]
public ActionResult AddSurveyPic(IEnumerable<CarShow_MVC.lmit_pics> picSelections)
{
// Save data here
}
Thanks.
Upvotes: 1
Views: 2991
Reputation: 1038710
Don't write loops in your views. I would recommend you to use editor templates:
@model IEnumerable<CarShow.lmit_pics>
@using (Html.BeginForm())
{
<div style="width:100%; height:60px; ">
<input type="submit" value="Add Selected Photo(s) to Survey" />
</div>
@Html.EditorForModel()
}
and then create a corresponding editor template which will automatically be rendered for each element of the model: ~/Views/Shared/EditorTemplates/lmit_pics.cshtml
. Notice the name and location of the template which are important:
@model CarShow.lmit_pics
<div style="width:296px; float:left">
<div style="float:left; width:200px; margin-bottom:18px">
@{string cropped = "../../../Content/Images/" + Html.DisplayFor(x => x.picname).ToString() + "?" + Html.DisplayFor(x => x.version).ToString(); }
<img alt="picture" class="pic-size" src="@cropped" />
<br />
@Html.EditorFor(x => x.brand)
</div>
</div>
You might also want to read the following article to better understand the naming conventions that the default model binder uses when binding collections and dictionaries.
Upvotes: 3