I'm working with Asp.net and MVC, creating a code where the person needs to enter month and year to perform a search. I created an Enum for the months of the Year, but I can't find it "right" to create an Enum for the years, as I would have to manually populate and each year add a new value.
In my Cshtml I had done it that way
<select name="ano">
@for (int i = DateTime.Now.Year; i > 1999; i--)
{
<option>@i</option>
}
</select>
But to go to the MVC standard, I wanted to put this information in an Enum inside my Model. Can I do something similar to dynamically place the years in an Enum?
CodePudding user response:
MVC does not prescribe that everything must be a class or enum. It makes no sense to have enum members representing years.
What were you going to name them, Y2021
and then strip the Y
? Or use their underlying numeric value, ignoring the label?
Just use a loop and an integer, like you do now.
CodePudding user response:
To approach to MVC standarts , you don't need to create any enums, you have to create a model
public ViewModel
{
public int Year {get;set;}
public List<SelectListItem> Years {get; set;}
}
and controller action
public ActionResult GetYear()
{
var years = new List<SelectListItem>();
for (var i = DateTime.Now.Year; i >= 1999 ; i--)
years.Add ( new SelectListItem { Value=i.ToString(),Text=i.ToString()});
var model=new ViewModel{ Year=2021,Years= years});
return View(model);
}
and view GetYear.cshtml
@model ViewModel
.....
<select class="form-control" asp-for="@Model.Year" asp-items="@Model.Years"></select>