Set model properties in view or controller?
Let's say you've got a Create View and Controller for Model TeddyBear
. Let's pretend TeddyBear
has an optional MommyBear
property (an int
), which is passed in as an id (via query string or just "example.com/Bears/Create/#"
There are two ways I could set the MommyBear
property on the new TeddyBear
:
In the view, with
@{
ViewBag.Title = "Create";
Model.MommyBear = Request["id"];
}
Or in the controller, with:
[HttpPost]
public ActionResult Create(TeddyBear bear, int id)
{
bear.MommyBear = id;
...
Is either method more efficient? Are there any dangers in using either one? Which is the best practi开发者_开发技巧ce?
I always use my controller to build my model and then have the view present that model however I see fit. To answer your question, set the property inside of your controller for best practices, that way if your Model changes, it isn't tied to your View. There are more patterns you could use such as the repository pattern and view models, but I think this answers your question.
I try to keep all logic outside of the view. In your Get method for Create on the Bears controller, set the MommyBear value in there and then bind that to the View as the model and it will already be set for you. HTH! ;)
if you have a route defined in global.asax like
routes.MapRoute(
"bear",
"{controller}/{action}/{MommyBear}",
new { action = "Index", MommyBear = "" }
);
and you have action method like
[HttpPost]
public ActionResult Create(TeddyBear bear)
{
//bear.MommyBear = id;//The Property will be automatically bound to Mommybear
}
Now only thing you have to do is to put this route before default one. This happens because modelbinder also looks into routevalue dictionary for values of your model besides other places (form post, json post, querystring etc.). However there is one thing to note that above route will always match and request will not get to
"{controller}/{action}/{id}" route
you can do another thing put http://localhost/Bear/Create?MommyBear=1 and model binder will bind Mommybear property from querystring.
Note I am not encouraging you to use query string or change your default route for binding purpose only. The purpose is to show the way model values can be populated
You should not update the model from your view. This is the controller's responsibility.
There is no reason to have a separate parameter for "Id" on your action method. Just add an Id property to your viewmodel and ASP.NET MVC will take care of the model binding for you.
精彩评论