views:

379

answers:

2

(That is, the model that you pass to the view and the model that you get back once the form posts.)

If not, is it better to do so anyways? What if there is data you are gathering that is beyond what the view page model has a property for?

A: 

I am a little unclear about the question, so correct me if I am wrong. I am assuming that you are talking about the model that you pass to the view and the model that you get back once the form posts.

No they don't have to be the same, you would probably have a fair bit of overlap though. The model going up to the view should contain all the fields that the Post one would as you would need to send the data back up if there were validation errors.

My models are the same, the reason is that the models I use usually contain only the properties corresponding to the elements on the form. If I need extra data, perhaps a page title, I would typically add that directly to ViewData.

If you have extra properties on the model class and you use automatic binding on Post, you have the issue where if someone modifies the Post request in transit and adds extra data corresponding to the unused properties in the model, you would have the automatic binder bind that data which in the worst case could be used for something like a SQL Injection attack (best case is your app is in an unknown state). So my advice is don't do that. If you absolutely must, say you have fields that get shown and hidden based on some other elements up the page, use manual binding and don't bind fields that shouldn't have data in them.

Dean Johnston
There's another possibility, ([Bind(Exclude="Field")] ViewModel data)
queen3
Ah so then could I bind it to my model excluding some fields and pull those excluded ones out from Request as needed... and keep my object ready to be dumped into the DB.
shogun
A: 

Sure you can use different classes in the controller's parameters than the one you send to the view, and that can often be quite useful. For example, I often have forms where I'm passing in a parent entity to the view, but the view is posting back a form that contains stuff that will become a new instance of a child entity. You can handle additional fields from the client too.

Model binding has attributes that deal with excluding properties in a bound class from attempting to load from binding

Here is an example:

public ActionResult AddComment( 
    [Bind(Exclude = "commentId"] Comment userComment, bool notifyUser
)
{

     // do stuff to add comment to the DB
     // notifyUser is a checkbox passed from client, but isn't stored in DB        

     // now return the comment view to the client but that view needs the entire thread

     var model = GetThread();
     return View("Comment", model);
}
Stephen M. Redd