简体   繁体   English

绑定对象永远不会为空

[英]Bound object never be null

For instance, there is some object that will be model for strongly-typed view: 例如,有一些对象将成为强类型视图的模型:

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

Further, some action exists in controller that will work with object specified above: 此外,控制器中存在一些可与上面指定的对象一起使用的操作:

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

So the question is why obj isn't a null while Index action first called? 所以问题是为什么在首次调用Index动作时obj不为null It's created new instance of SomeModel class with null SomeUsualField . 它使用null SomeUsualField创建了SomeModel类的新实例。

The ASP.NET MVC model binding infrastructure tries to fill all properties with data coming from the request object (query string, form fields, ...). ASP.NET MVC模型绑定基础结构尝试用来自请求对象(查询字符串,表单字段等)的数据填充所有属性。 Therefore it creates an instance of all parameters of the controller to try to match the properties. 因此,它将创建控制器所有参数的实例以尝试匹配属性。 Because you don't pass a SomeUsualField, it is null, but the parameter object has an empty instance. 因为您没有传递SomeUsualField,所以它为null,但是参数对象具有空实例。

You can initialize the property SomeUsualField when you call http://localhost/MySite/MyController/Index?SomeUsualField=test . 您可以在调用http:// localhost / MySite / MyController / Index?SomeUsualField = test时初始化属性SomeUsualField。 The property SomeUsualField will automagically initialized with 'test' SomeUsualField属性将自动用'test'初始化

If you don't want the parameter to be set, you can leave it away and make a 2nd action with the attribute [HttpPost]. 如果您不想设置参数,则可以将其保留,并使用属性[HttpPost]进行第二次操作。 A good tutorial is the music store . 音乐商店是一个很好的教程。

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

[HttpPost]
public ActionResult Index(SomeModel obj) 
{  
    // update logic
    return View(obj); 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM