A linked object is never zero

For example, there is some object that will be a model for a strongly typed representation:

class SomeModel { public string SomeUsualField { get; set; } } 

In addition, there is some action in the controller that will work with the above object:

 public ActionResult Index(SomeModel obj) { return View(obj); } 

So the question is, why is obj non- null and is the Index action called first? He created a new instance of the SomeModel class with null SomeUsualField .

+4
source share
1 answer

The binding framework of the ASP.NET MVC model tries to populate all the properties with data coming from the request object (query string, form fields, ...). Therefore, it creates an instance of all the controller parameters in order to try to match the properties. Since you are not passing SomeUsualField, it is null, but the parameter object has an empty instance.

You can initialize the SomeUsualField property when you call http: // localhost / MySite / MyController / Index? SomeUsualField = test . The SomeUsualField property will be automatically initialized using 'test'

If you do not want the parameter to be set, you can leave it and do the second action with the [HttpPost] attribute. A good tutorial is a music store .

 public ActionResult Index() { var obj = new SomeModel(); return View(obj); } [HttpPost] public ActionResult Index(SomeModel obj) { // update logic return View(obj); } 
+2
source

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


All Articles