Reputation: 15423
i'm using the following post type:
<% using (Html.BeginForm())
{ %>
<%= Html.Hidden("EligiblePages", Model.EligiblePages) %>
.... no elements in list appear
$('.btnAction').click(function() {
$.post("Home/AddProduct", $('form').serialize(), function(retval) { $('#addProductDialog').html(retval); });
});
public class ProductViewModel
{
public List<string> EligibleProducts { get; set; }
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddProduct(string sender, ProductViewModel model)
{
...
}
i'll update this when i get home and can put together a more precise example.
and in my ViewModel that is getting posted i have a list<string>
as a hidden input field. for some reason when the post occurs and i inspect the controller post method that field is not coming over correctly. any ideas?
Upvotes: 1
Views: 845
Reputation: 1802
<%
for(int i=0;i<Model.EligiblePages.Count;i++)
Html.HiddenFor(model=>model.EligiblePages[i]);
%>
This would render hidden input elements and would serealize to your model appropriately when then controller function AddProduct gets called.
Upvotes: 4
Reputation: 33071
Based on your View Model, I would expect your form elements to look like this:
<input type="hidden" name="EligibleProducts[0]" value="whatever" />
<input type="hidden" name="EligibleProducts[1]" value="whatever" />
etc.
That's what the default model binder is expecting.
Upvotes: 1
Reputation: 125488
The DefaultModelBinder
will expect one or more form elements to be posted to bind to the List<string>
where the name of each form element matches the name of the list property on the ViewModel. Phil Haack wrote a good blog post about various collection binding approaches.
If you have the entire collection rendered in one hidden input as seems to be suggested in your question, then what will be sent to the browser will just be one value to bind to the list and not a collection of values. You may want to enumerate over the collection and render each value in a hidden input. You could also implement your own model binder to dictate how the posted values are bound to the ViewModel, although that is probably overkill in this case.
What do you see being posted for the collection if you use a HTTP debugging proxy tool like fiddler?
Upvotes: 0