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"; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With