ASP.net MVC View Model vs ViewData.Model?

I am studying asp.net mvc and found something interesting:

It seems that I cannot explicitly determine the Model view from the view with the error message stating that it has no setting.

@{ this.Model = "Hello" } //error

Then I looked at the source code in WebViewPage.cs and the View Model property actually looks like this:

public object Model { get { return ViewData.Model; } }

So the error.

But I wonder how I can do this: @{ ViewData.Model = "hello"; } @{ ViewData.Model = "hello"; } and really be able to use the @model operator, the result is "hello"

I think I delve too much into this, but why is this so?

new to C # and ASP.NET

+6
source share
4 answers

Rule - Concern Separation ... In MVC, the Controller delivers the model to the view, and it will always be the controller that can set / assign the model for the view ... that Views can use ... This is by design ... the game by the rules - this is what i would say ... and if you are studying MVC, thatโ€™s great, and I highly recommend you read

Stevens Sanderson MVC Book

+7
source

Things like ModelBinders and the fact that sometimes you donโ€™t need to change the model in context, so they need a tuner. Another reason is to facilitate unit testing.

However, you rarely had to do it yourself in the submission, so abuse it at your own peril and risk.

+2
source

This is the pit of success design design theory. You do not have to change the property of the model in your view, so it is becoming increasingly difficult for them to do this. But since there may be times when you have no choice, they do not make it impossible.

+2
source

There is no magic here. In the first case (as you indicated) there is no property for the model property. Therefore, you cannot assign anything. And that makes sense - why do you need to reassign the model from the inside?

In the second case, you intercept this restriction using the ViewData.Model function. Since this is an object type, you can assign something.

(BTW, I assume that in the first code snippet you assign "Hello", not "Hello")

+1
source

Source: https://habr.com/ru/post/911904/


All Articles