HTML select value missing from MVC model after post

In my MVC project, I have a property that is either Y or N. No maybe, no empty string – “Y” or “N”.

public class Coaster {
     public string DoYouLikeCoasters { get; set; }
}

I first thought just to do a basic select element. Something simple:

<select id=”DoYouLikeCoasters”>
     <option value=”Y”>Y</option>
     <option value=”N”>N</option>
</select>

But when I checked the model in the controller after the form was posted, the “DoYouLikeCoasters” property was empty. I basically hadn’t told MVC that I wanted the property. In order to properly get the value to the controller, I needed to MVC-ify the select by using the Html.DropDownListFor. Since I just wanted “Y” and “N” as values, I still wanted to essentially hard-code the values. So here is how I did that:

@Html.DropDownListFor(model => model.DoYouLikeCoasters, new SelectListItem[] {
     new SelectListItem() { Value = “Y”, Text = “Y” },
     new SelectListItem() { Value = “N”, Text = “N” }
}, new { @class = “form-control”, @style = “width: 50px” })

Advertisements
  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: