开发者

MVC post not populating the model

I cannot figure out why my model is not being populated. All the data posted is in the Request.Form, but the model is actually turning out to be null.

According to this answer on model with collection not populating on postback

In other words, (...) If any required fields are missing, or if the values are submitted in such a way that they cannot be converted to the type of a required field, then the entire object will be left null

I have changed several value types, but I cannot get it to work.

Here is my model:

public class AddModel
{
    //Get properties 
    public Vehicle vehicle; 

    //Post properties 
    [Required(ErrorMessage = "Please enter a start date")]
    public DateTime StartDate; 
    public int? Status开发者_开发问答Code; 

    public SelectList StatusCodes()
    {
         ...
    } 
}

Can you think of why it's not being populated?


Making AddModel members Properties - adding get; set; to fields should solve your problem


As per @archil's response, you should make your public variables properties. Although this may work with types you will run into problems as soon as you add complexity. Certainly for classes but possible for nullable types too.

The model binders use reflection to parse the form fields into the model, and reflection works differently on properties to public variables - in the case of these models, the differences will likely be causing the failure here.

Hope that helps - and hat tip to @archil for answering this (probably) correctly, much sooner than me!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜