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?
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.
To approach to MVC standarts, you can do something like this
public ActionResult GetYear()
{
var model=new ViewModel{ Year=2021,
Years= Enumerable.Range( 1999, DateTime.Now.Year -1998)
.OrderByDescending(x=>x)
.Select(x => new SelectListItem { Value=x.ToString(),Text=x.ToString()});
return View(model);
}
GetYear.cshtml
@model ViewModel
.....
<select class="form-control" id="levels" asp-for="@Model.Year" asp-items="@Model.Years"></select>
and ViewModel class
public ViewModel
{
public int Year {get;set;}
public List<SelectListItem> Years {get; set;}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.