Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"; } 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

like image 839
Jan Carlo Viray Avatar asked Mar 28 '12 23:03

Jan Carlo Viray


3 Answers

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

like image 120
NiK Avatar answered Nov 14 '22 14:11

NiK


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.

like image 40
moribvndvs Avatar answered Nov 14 '22 14:11

moribvndvs


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.

like image 2
Jonathan Allen Avatar answered Nov 14 '22 14:11

Jonathan Allen