I have the following ViewModel:
public class MyViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public int ParentClassId { get; set; }
public List<AnotherClass> AnotherClassItems { get; set; }
}
And in the view I only have a form input for Title, and a list of AnotherClassItems that aren't editable - they are just used to display a list of items related to the class. All of the properties are set when the 'edit' view loads, but when the view does a post, the ParentClassId & AnotherClassItems lists are null. Here is the HttpPost ActionResult from the controller:
[HttpPost]
public ActionResult Edit(FormCollection collection, MyViewModel myviewmodel)
{
if (ModelState.IsValid)
{
//myviewmodel.ParentClassId and myviewmodel.AnotherClassItems are null??
}
return View(myviewmodel);
}
Is there a way to pass the ParentClassId & AnotherClassItems properties without having them as form inputs in the view? Or should I use the Viewbag for this?
@Html.HiddenFor(model => model.ParentClassId)
if your requirement actually means "without VISIBLE form inputs in the view. Can you tell us why you want to also pass the List on POST? There are lots of MVC examples of this exact pattern and I think you may find this approach is not the way most of the examples handle the problem. HINT: you really don't want to send that entire List back across the wire on POST -- there are better ways to get at that same data at that point in the processing. – David Tansey