Reputation: 2506
In my MVC5 app I have a page which shows logs.
I have a drop down to filter logging levels, which are:
I have these defined an an enum called ErrorLevel:
public enum ErrorLevel
{
[Description("All")]
All = 0,
[Description("Debug")]
Debug = 1,
[Description("Error")]
Error = 2,
[Description("Info")]
Info = 3
}
I am rendering these in my view like this:
@Html.EnumDropDownListFor(model => model.Level)
The drop down value is blank when the page first renders - how do I have
All
as the default selected enum value when the page first renders?
I've spent 20 minutes looking for how to do this but can't find how to do it, can anyone help?
Upvotes: 2
Views: 793
Reputation: 1612
Hi you can easily do that, in the constructor of the model class within controller .
Here is the complete example:
Sample Modal Class:
public class SampleModel
{
public ErrorLevel level{ get; set; }
}
Enum:
public enum ErrorLevel
{
[Description("All")]
All = 0,
[Description("Debug")]
Debug = 1,
[Description("Error")]
Error = 2,
[Description("Info")]
Info = 3
}
Some Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
SampleModel samplemodel= new SampleModel {level= level.All}; //you can set any value which you want as default
return View("View",samplemodel);
}
}
Hope the above code was helpful
Thanks
Karthik
Upvotes: 3
Reputation: 5260
You can do this by setting the Enum in the Model before it gets called in the view.
Controller
model.Level = ErrorLevel.All;
Upvotes: 1