[英]Can I populate Enum with For in C#?
I'm working with Asp.net and MVC, creating a code where the person needs to enter month and year to perform a search.我正在使用 Asp.net 和 MVC,创建一个代码,人们需要输入月份和年份来执行搜索。 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在我的 Cshtml 中,我是这样做的
<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.但是对于 MVC 标准的 go,我想将此信息放在我的 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. MVC 并未规定所有内容都必须是 class 或枚举。 It makes no sense to have enum members representing years.让枚举成员代表年份是没有意义的。
What were you going to name them, Y2021
and then strip the Y
?你打算给它们取什么名字, Y2021
,然后去掉Y
? Or use their underlying numeric value, ignoring the label?还是使用它们的基础数值,忽略 label?
Just use a loop and an integer, like you do now.只需使用一个循环和一个 integer,就像现在一样。
To approach to MVC standarts, you can do something like this要接近 MVC 标准,您可以执行以下操作
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获取年份.cshtml
@model ViewModel
.....
<select class="form-control" id="levels" asp-for="@Model.Year" asp-items="@Model.Years"></select>
and ViewModel class和 ViewModel class
public ViewModel
{
public int Year {get;set;}
public List<SelectListItem> Years {get; set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.