Why is my model attribute null?

While I can’t explain every reason, here is one reason I found. First, my rather simple model:

    public class User {
        public string ID { get; set; }
        public string Email { get; set; }
        public Guid SecretId{ get; set; }

I was manually populating the model from the database and passing it off to the view from the Home controller like so:

     public ActionResult Index(string id) {
         User user = new User();
         user.ID = id;
         // Various other stuff...
         user.SecretId = Guid.NewGuid();
         return View("Index", user);

The user can do some simple modifications in the view, but it’s not terribly complex. Then perform a POST:

   @model ScottProj.Models.User
    @using (Html.BeginForm("Process", "Home", FormMethod.Post)) {         @Html.LabelFor(m => m.ID)         @Html.LabelFor(m => m.Email )         @Html.TextBoxFor(m => m.Email )             }

When it got to the Process controller action, the “SecretId” was missing, most likely because there wasn’t anyplace in the view that there field was referenced, no form field that says “This is the SecretId value”. I didn’t want to show that value on the screen, so instead, I added a hidden field to hold that value:

   @Html.HiddenFor(m => m.SecretId)

And that did. My view now had a placeholder for the value so it could be sent back to the controller in the POST request.



  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: