This may be a duplicate, so I have indicated where my reading from this site has allowed me some progress...
I have a model defined as follows:
public enum RequestType
{
[Display(Name = "Lovely Cold Beer")]
Beer = 0,
[Display(Name = "Warm Tea")]
Tea = 1,
[Display(Name = "Milky Coffee")]
Coffee= 2
}
Based on the URL, I have a variable that will be used to automatically select the appropriate list item, e.g.
http://example.com/Request/Tea
will do this in the controller...
ViewBag.RequestType = RequestType.Tea.ToString();
return View("Index");
In my view I have a variable to read this value back, which then displays appropriate content:
if (ViewBag.RequestType != null)
{
reqType = Enum.Parse(typeof(RequestType), ViewBag.RequestType);
}
In this view I create a drop down list using:
@Html.EnumDropDownListFor(model => model.RequestType, htmlAttributes: new { @onchange = "YadaYada();" })
This renders the list using the Display Name
values defined for each Enum
. What I need is to automatically select the appropriate list item when the page is rendered, that matches the value of reqType
.
From my research I see that I can pass in the variable like so:
@Html.EnumDropDownListFor(model => model.RequestType, reqType.ToString(), htmlAttributes: new { @onchange = "YadaYada();" })
But this creates a new list item containing the enum value and not the display name, e.g.
Tea <-- This should not be created, instead 'Warm Tea' should be selected
Lovely Cold Beer
Warm Tea
Milky Coffee
My entire approach may be wrong as I'm new to MVC, but I'd welcome advice to fix it please! I don't understand why in the controller, using ToString
on the enum value creates a different outcome to doing the same in the EnumDropDownListFor
method.