I am new to asp.net mvc4 and there is something i don't understand well.
Why do I have to declare the Model using @model at top of the view, if I already pass an object to the View in the controller.
Taking an example :
Controller:
public ActionResult countryDetails(int id)
{
Country country = db.Country.Find(id);
return View(country);
}
View:
@model MvcApplication2.Models.Country
@{
ViewBag.Title = "countryDetails";
}
...
The controller returns a View with an object as parameter, so the model should be already known. I'm sorry if it is obvious, but I can't figure out why this is not a "double" declaration.
Thanks for you help !
How to specify a model for the razor view in asp.net mvc? To specify a model for the View, we can using @model statement at the top of the View page.
To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.
The declaration at the top will do two things for you: It will allow intellisence to know what type you are using when you type in @Model or use any of the Html helper extensions. It will also check at runtime that model passed in can be cast to the type the view expects.
Right click the Views\HelloWorld folder and click Add, then click MVC 5 View Page with Layout (Razor). In the Specify Name for Item dialog box, enter Index, and then click OK. In the Select a Layout Page dialog, accept the default _Layout. cshtml and click OK.
The declaration at the top will do two things for you:
It will allow intellisence to know what type you are using when you type in @Model or use any of the Html helper extensions.
It will also check at runtime that model passed in can be cast to the type the view expects.
Its not necessarily a "double declaration" as it is analogous to specifying a type to a parameter on a method. Like so
Person Someone = new Person();
RenderView(Someone);
...
void RenderView(Person model) { }
By default your view inherits from System.Web.Mvc.WebViewPage<TModel>
You can optionally override this class, it's default ASP.NET inheritance mechanism:
@inherits System.Web.Mvc.WebViewPage<List<CompanyName.MyProduct.MyCategory>>
Or you can just simplify this since MVC3 like this:
@model List<CompanyName.MyProduct.MyCategory>
This sugar syntax was made to simplify code typing. This declaration give you some things
Just believe that this is a method which accepts object and cast it to the specified type that you provide
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