How MVC View works even without specifying Model type?

Just created a simple MVC 5 application.

Created a controller and calling my view like this:

var testClass = new TestClass();
testClass.Name = "Krish";
return View(testClass);

Created a view and it looks like below:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<h3>@Model.Name</h3>

But this just works even without specifying the Model type.


Should not we specify something like:
`@Model TestClass`

Any ideas why?

EDIT:
This page of MSDN says that Represents a container that is used to pass strongly typed data between a controller and a view. We are not strongly typing the model above. How come then the view find the model type then ?

Upvotes: 2

Views: 1146

Answers (2)

dav_i
dav_i

Reputation: 28107

A cshtml view (or vbhtml if you're that way inclined) is actually turned into a .NET class which inherits from WebViewPage<TModel>.

When you declare in a view

@model SomeType

your telling the MVC framework to declare your view like so:

public class _Page_Path_To_MyView_cshtml : WebViewPage<SomeType> { ... }

When you omit the @model declaration, the framework declares your view like this:

public class _Page_Path_To_MyView_cshtml : WebViewPage<dynamic> { ... }

Effectively all Views without a @model declaration can be thought of as having

@model dynamic

at the top, which is why your @Model.Name still works, though you will notice that won't have intellisense (unless you use it more than once).

If you did @Model.SomePropertyThatDoesntExist you'll get an exception.

Upvotes: 4

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

It can work this way, but it is convention that View should be strongly typed.let's understand this with an example.

Suppose you have two models:

public class Model1
{
public string Name {get;set;}
}

public class Model2
{
public string FullName {get;set;}
}

Now if you have this in View:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<h3>@Model.Name</h3>

and from action you do:

var Model= new Model1();
Model.Name = "Ehsan";
return View(Model);

All will be fine, but if you pass like this:

var Model= new Model2();
Model.FullName = "Ehsan Sajjad";
return View(Model);

now you view will throw exception because this Model does not have Name property.

Upvotes: 1

Related Questions