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 practice?
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! 😉