[英]How do I create a reusable dropdown list
I'm after creating a really simple drop-down list, which essentially shows various times, and their value is the minutes past midnight for each time. 我创建了一个非常简单的下拉列表,该列表实际上显示了各个时间,它们的值是每次午夜后的分钟数。 For example: 例如:
Value Time
60 01:00 AM
75 01:15 PM
90 01:30 PM
105 01:45 PM
120 02:00 PM
etc 等等
The thing is, I need to use the same drop-down list in a whole bunch of views and controllers in my application. 关键是,我需要在应用程序中的所有视图和控制器中使用相同的下拉列表。 After reading a couple of articles, it seems like I need to create a static class for this? 看了几篇文章之后,看来我需要为此创建一个静态类吗? But all the examples seem to be way more complicated than I actually need. 但是所有示例似乎都比我实际需要的复杂得多。 Is it an IList
that I should be creating for this? 我应该为此创建一个IList
吗?
You could try the following method 您可以尝试以下方法
public static class DropdownData
{
public static IList<SelectListItem> GetTimeList(string defaultValue)
{
var times = new List<SelectListItem>();
times = Enumerable.Range(4, 4).Select(x => {
var minute = x * 15;
var time = DateTime.Today.AddMinutes(minute);
return new SelectListItem()
{
Value = minute.ToString(),
Text = time.ToString("hh:mm tt"),
Selected = (!string.IsNullOrEmpty(defaultValue) && minute.Equal(defaultValue))
};
}).ToList();
return times;
}
}
@Html.DropDownList("TimeList", DropdownData.GetTimeList("75"), new { @class = "form-control" })
If you need a value to be Global
, then yes, you'll want it to be public static
in C#. 如果需要将值设为Global
,则可以,在C#中将其设为public static
。 I recommend also putting it in a public static class
so you can access it by name. 我建议还将其放在public static class
以便您可以按名称访问它。
public static class MyData
{
public static IEnumerable<DateTime> ValueTimes { get; set;} //(or IList or List<T> or whatever you want)
}
public class IDoStuff
{
public DateTime myTime { get; set; }
public IDoStuff(DateTime d) //constructor
{
if(ValueTimes.IndexOf(d) != -1) //-1 says I no findie
myTime = d;
else
throw new ApplicationException("That's not a valid time, dummy");
}
}
See, easy peasy. 看,轻松自在。 Also, use DateTime
or TimeSpan
, even if it's all in the same day. 另外,使用DateTime
或TimeSpan
,即使它们都在同一天。 Don't use strings
to represent time, you're asking for trouble that way. 不要使用strings
来表示时间,而是用这种方式来寻求麻烦。
Edit: While I was putting up the solution, you posted sample data. 编辑:在我提出解决方案时,您发布了示例数据。 Given this: 鉴于这种:
Value Time
60 01:00 AM
75 01:15 PM
90 01:30 PM
105 01:45 PM
120 02:00 PM
I think you can actually just do this and skip the static variable: 我认为您实际上可以执行此操作并跳过static变量:
public static Timespan GetTime(int value)
{
return Timespan.FromMinutes(value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.