Archive for March, 2017

Converting a List of strings to a SelectList

I had a brief list of comma-separated strings that I was storing in the web.config file, and I needed to convert them into a SelectList to bind to a DropDownListFor control in MVC. For that, there was a very simple method:

TempData["FundingTypes"] = new SelectList(ConfigurationManager.AppSettings["CoasterTypes"]
     .Split(',').ToList());

If I had needed a List<SelectListItem> instead, I would have done this:

            TempData["FundingTypes"] = ConfigurationManager.AppSettings["CoasterTypes"]
                .Split(',')
                .Select(f => new SelectListItem() {
                    Text = f.ToString(),
                    Value = f.ToString()
                }).ToList();

Leave a comment

Showing MVC ModelState errors in the view

I wanted to show the various ModelState errors encountered in an MVC controller and display them in the view. So in my controller, I have a bit of code that loops through the errors and builds them in a string, adding an HTML line break between each error:

string errors = String.Empty;

foreach (ModelState modelState in ViewData.ModelState.Values) {
     foreach (ModelError error in modelState.Errors) {
          errors += “<br />” + error.ErrorMessage;
     }
}

ViewBag.Message = “The following errors have occurred: “ + errors;

In the view, I show my ViewBag variable. Notice that I use the Html.Raw method to display the HTML code properly in using Razor:

@Html.Raw(ViewBag.Message)

 

Leave a comment

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" })

Leave a comment