Model declaration in Razor View in mvc4 asp.net

I am new to asp.net mvc4 and I do not understand something.

Why do I need to declare a model using @model at the top of the view if I already pass the object to the view in the controller.

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 the object as a parameter, so the model should already be known. Sorry if this is obvious, but I can’t understand why this is not a “double” expression.

Thanks for the help!

+6
source share
3 answers

The ad above will do two things for you:

  • This will let intellisence know what type you are using when entering @Model or using any Html helper extensions.

  • It also checks at runtime that the model passed can be cast from the type that the view is waiting for.

This is not necessarily a “double declaration” because it is similar to setting the type to a method parameter. In this way

 Person Someone = new Person(); RenderView(Someone); ... void RenderView(Person model) { } 
+6
source

By default, your view inherits from System.Web.Mvc.WebViewPage<TModel>

You can optionally override this class, the default ASP.NET inheritance mechanism:

 @inherits System.Web.Mvc.WebViewPage<List<CompanyName.MyProduct.MyCategory>> 

Or you can simply simplify this, since MVC3 is like this:

 @model List<CompanyName.MyProduct.MyCategory> 

This sugar syntax has been simplified to enter code. This announcement gives you some things.

  • View automatic casting object with preferred type
  • You get a "model" property defined by a type that allows you to access your object methods and properties.

Just believe that this is a method that takes an object and passes it to the specified type that you provide

+2
source

The main reason is type safety, it allows you to work with strongly typed representations with the benefit of intellisense, compiler error hints, invalid casting, etc.

In addition, another reason is readability - it acts as a reminder of which model you are actually working on, rather than continuing to contact the controller.

+1
source

Source: https://habr.com/ru/post/950628/


All Articles