1
votes

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?

1
you can use a query string. nothing else. even viewbag will fail.Dave Alperovich
You should be able to get part of what you want by adding @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
I'm trying to avoid using a hidden form input for security reasons. There will be multiple users in this app and I don't want them to be able to modify the posted data and save items under other ParentClassId's. Am I correct in thinking that this would be a possibility with hidden form inputs?jk105
And as for passing the List on POST - I just want to display the List again once the Edit action has been posted. I guess I don't want to hit the database again to get the List, just to save on db requests - but I'll be saving data to the db within the action controller, so an extra retrieval query won't be too much of an overhead. Is this the best way to display the List? - to get it from the db again? I come from a webforms background where this was all done with the viewstate - I'm still learning MVC and working out best practices.jk105

1 Answers

0
votes

Remember, the form only posts back HTML input fields. So if you did not make any text boxes or hidden boxes they will not post to your Edit action.

The correct way to handle this is by passing the ID as a hidden field, then pulling the original values from your database/repository.

Then apply the new values for Title and AnotherClassItems to your model and save to the repository/database.