This is not that important, but I’m getting conflicting information about this so I thought of ask here.
Let’s say I have a simple Controller and I want to pass the Model to the View. Most of the time I see it like this:
[HttpGet]
public ActionResult Foo() {
var bar = new SomeModel() {
Id = 1,
Name = "John Dork",
Email = "some@email.something"
};
ViewData.Model = bar;
return View();
}
Or like this:
[HttpGet]
public ActionResult Foo() {
var bar = new SomeModel() {
Id = 1,
Name = "John Dork",
Email = "some@email.something"
};
return View(bar);
}
Questions: Although I’m not aware of a difference between these two ways of sending this data to the view, is there in fact a difference? And what is different about them? What would be the “correct” way of doing this?
Thanks
They are equivalent. In the MVC source code,
View(object)is defined as:Which in turns calls:
And you can see that it just sets
ViewData.Model.There’s no “correct” way of doing it, but I feel that the second approach (i.e., not using
ViewData.Model) is more fluent and pleasing.