I'm developing a web application with asp.net mvc 3 and trying to modify a list which is contained in my ViewModel and then post it with JQuery change to my controller. The problem is the ViewModel contains no values on arrival.
The ViewModels looks like this:
public class OfferListViewModel
{
public List<OfferViewModel> Offers { get; set; }
}
public class OfferViewModel
{
public Guid Id { get; set; }
public double Total { get; set; }
}
Controller method:
[Authorize]
public ActionResult Index()
{
OfferList list = this._offerService.GetOfferListById(1234);
OfferListViewModel model= new OfferListViewModel
{
Offers = list.OfferListProducts.Where(o => o.Product.ProductCategory == (int)ProductCategory.Print).ToViewModel().ToList()
};
return View(model);
}
list.OfferListProducts is an IEnumerable converted with a helper ToViewModel() and finally ToList()
[HttpPost]
[Authorize]
public ActionResult UpdateOfferList(OfferListViewModel offers)
{
// do something
}
View:
@model Models.OfferListViewModel
<form id="mywall-updateofferlist-form" class="form-horizontal" action="@Url.Action("UpdateOfferList", "MyWall")" method="post">
@Html.HiddenFor(model => model.ProductCategory)
<table class="table table-hover">
<thead>
<tr>
<th>Total</th>
</tr>
</thead>
<tbody>
@for (int count=0; count < Model.Offers.Count(); count++)
{
@Html.HiddenFor(model => model.Offers[count].Id)
<tr>
<td>@Html.EditorFor(model => model.Offers[count].Total)</td>
</tr>
}
</tbody>
</table>
</form>
JavaScript:
<script type='text/javascript'>
$(function () {
$('form[id=mywall-updateofferlist-form]').change(function () {
if ($(this).valid()) {
$.post($(this).attr('action'), $(this).serialize(), function (data) {
if (data.success) {
// do something
} else {
// do something else
}
});
return false;
}
});
});
</script>
Can someone spot a mistake? I have a lot more attributes in the ViewModels which are not necessarily needed in my controller post method and thus not mapped/left out to simplify the description here. Could this be a problem somehow? The Id is mapped with HiddenFor and should therefor be contained in the ViewModel after post and other values should be null?
Edit:
Firebug post:
Offers[0].Id 1c5bdc21-8f8c-4ad2-a4a0-49e4011e3ba6
Offers[0].Total 0.6
Offers[1].Id 12ede957-8a7e-47a9-8e86-a388d60ea2d9
Offers[1].Total 1.12
Offers%5B0%5D.Id=1c5bdc21-8f8c-4ad2-a4a0-49e4011e3ba6&Offers%5B0%5D.Total=0.6&Offers%5B1%5D.Id=12ede957-8a7e-47a9-8e86-a388d60ea2d9&Offers%5B1%5D.Total=1.12
My problem is similar to this: View Model IEnumerable<> property is coming back null (not binding) from post method?
But I have converted my IEnumerable to a List which is correctly displayed but not mapped when posted back to the controller.