GuyOlivier
GuyOlivier

Reputation: 183

MVC .NET razor DropDownList

I cannot link dropdownlist to my model in the view. I have the error message: The ViewData item that has the key 'title' is of type 'System.String' but must be of type 'IEnumerable with the following code:

public class FareCustomer
{
    [Required]
    public int title { get; set; }

My controller:

List<SelectListItem> titleList = new List<SelectListItem>();
titleList.Add(new SelectListItem { Text = "Non renseigné", Value = "0" });
titleList.Add(new SelectListItem { Text = "Monsieur", Value = "1" });
titleList.Add(new SelectListItem { Text = "Madame", Value = "2" });
titleList.Add(new SelectListItem { Text = "Mademoiselle", Value = "3" });
ViewBag.title = titleList;
//Create a new customer
FareCustomer fareCustomer = new FareCustomer();
fareCustomer.title = 1;
return View("CreateAccount", fareCustomer);

My view 'CreateAccount'

@model PocFareWebNet.Models.FareCustomer
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    @Html.DropDownList("title")
    <input type="submit" value="Save" />
</fieldset>
}

I tried to apply what is described here: Using the DropDownList Helper with ASP.NET MVC but obviously I missed something.

Upvotes: 2

Views: 5315

Answers (3)

GuyOlivier
GuyOlivier

Reputation: 183

I found my issue. I used the view generated by Visual Studio and it already defines ViewBag.Title

@model PocFareWebNet.Models.FareCustomer
@{
   ViewBag.Title = "CreateAccount";
}

This is why the error says the type is string and cannot be converted to IEnumerable.

It seems razor is not case sensitive: The controller set ViewBag.title but the view set ViewBag.Title and overwrites ViewBag.title coming from the controller.

Thank you for your help.

Upvotes: 2

Murali Murugesan
Murali Murugesan

Reputation: 22619

Try casting to IEnumarable and use model based helper

@Html.DropDownListFor(m => m.title,((IEnumerable<SelectListItem>)ViewBag.title))

Upvotes: 2

R&#233;da Mattar
R&#233;da Mattar

Reputation: 4381

Try this instead :

@Html.DropDownListFor(model => model.title, (SelectList)ViewBag.title)

The first argument will be receiving your selected value.

Upvotes: 1

Related Questions