简体   繁体   中英

ASP.net MVC View's Model vs ViewData.Model?

I'm learning asp.net mvc and found something interesting:

It seems that I can't explicitly define a View's Model from within the View with error message saying that it has no setter.

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

Then I looked at the source code in WebViewPage.cs and a View's Model property is actually like this:

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

Thus the error.

But it's interesting how I can do this: @{ ViewData.Model = "hello"; } @{ ViewData.Model = "hello"; } and actually be able to use the @model statement, resulting to "hello"

I think I'm looking too much into it, but why is this so?

beginner at C# and ASP.NET

The rule is Separation of Concern...In MVC, a Controller supplies a Model to a View and it will always be the controller that can set/assign a Model to a view....which the Views can use...this is by design...play by rules is what I would say...and If you are learning MVC its great and I would strongly recommend you to read

Stevens Sandersons MVC book

Things like ModelBinders and what not sometimes need to change the model in context, so they need the setter. Another reason is to facilitate unit testing.

However, you would seldom need to do this yourself in views, so abuse it at your own risk.

It is the "pit of success" theory of API design. You aren't supposed to alter the Model property in your view, so they make it harder to do so. But since there may be cases where you have no choice, they don't make it impossible.

There is no magic here. In the first case (as you pointed out), there is not property setter for a Model property. So, you cannot assign anything. And that makes sense -- why do you need to re-assign model from within view?

In the second case you hack/bypass that constraint using ViewData.Model directly. Since it's of Object type, you can assign anything.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM