I know its a very silly question, but i have a little confusion on it, as i was answering a question today, i got confused in the comment of the questioner.
If i do like this in action:
public Action Result Index()
{
return View();
}
and my view:
@model MyModel
@Html.TextBoxFor(x=>x.Name)
and if i write action like this:
public Action Result Index()
{
return View(new MyModel());
}
what is the difference between these two actions, because i don't pass empty initialized model in that case also view is rendered.
I am attaching link as well of reference question its here: View Model Null when not explicitly passed by controller to strongly typed view
VIEW () : You are passing nothing in view from controller action method . So although it is strongly typed there is no data to bind to it .
VIEW (Model instance) : You are passing model instance to view which will be also used but in contrary to first one here , data Binding will be done through the HTML helpers we are using . +One shouldbe careful the view model you passed should be matching with the @model MyModel
Regards
First method
The first code is used as a simple return statement.
This code would simply return the current View. With the values and data that the view has initially for itself.
Second method
For example with code: https://stackoverflow.com/a/17276334/1762944
Whereas the other code, you're trying to use is having a new parameter in it.
The method would return a view, but this time it would have new values. The values that other model is having for itself.
You're more likely to be knowing the usage of
class
it is instantated using the new prefix and then the class name. Similarly, here a new Model is being passed to the View to update the content of that view.More like, just a parameter to change the values in the view.
The answer comes down to how lambda expressions such as
work. In the end, the expression does not care if your model is null or not as it figures out how to render the textbox by looking at the defined property of the strongly-typed class you have defined.
So if you had class:
and then in your veiw you reference your model like
If you look at the source of TextBoxFor
Generic types are used. So, since you have a strongly typed view with
Type TModel is MyModel and used with the HtmlHelper. Also
is composed with a
and thus the expression can be evaluated with both the model type and property type known. It does not matter whether you have an actual instance of the model or not.
The difference is that when you use
@model
in your view, you're not creating a new instance of that, you're just telling the view engine what strongly typed model you're using. It still needs to have the data passed to it from your controller. So by usingreturn View(new MyModel())
you're passing your view a default instance ofMyModel
. When you're usingreturn View()
you're passing your viewnull
.