我正在使用Intranet,特别是每周监控工具,该工具可让我逐周看到我的员工的活动。我正在致力于逐周过滤器。到目前为止,我已经找到了如何创建一个包含List
2015年每星期按以下格式:DownDownList问题显示类型
From dd/mm/yyyy to dd/mm/yyyy
像这样:
public ActionResult WeeklyMonitoring()
{
ProjectResourceManagerService pr = new ProjectResourceManagerService(new ModelStateWrapper(this.ModelState));
List<string> wl = pr.FetchWeeks(DateTime.Now.Year); // Creates the list
ViewBag.Weeks = wl;
wl.Select(m => new SelectListItem { Text = m, Value = m });
return View();
}
但这里的问题,当我选择一个星期我DropDownList
(这里我不得不将其转换为正确的类型):
<td><%: Html.DropDownList("Weeks", ((List<string>)ViewBag.Weeks).Select(m => new SelectListItem { Text = m, Value = m }), new { onchange = "this.form.submit();"}) %></td>
它发送至:
[HttpPost]
public ActionResult WeeklyMonitoring(FormCollection form)
{
string week = form["Weeks"];
ViewBag.Weeks = week;
return View();
}
我得到了明显的以下错误:
无法转换类型 '字符串' 到 'System.Collections.Generic.List'
我怎么可能避免这个错误,并保持表格发送后我的DropDownList
选定的一周?
编辑:
到目前为止,我已经发现了这个解决方案,可能不是一个过滤器实用但在这里我去:
[HttpPost]
public ActionResult WeeklyMonitoring(FormCollection form)
{
string week = form["Weeks"];
ProjectResourceManagerService pr = new ProjectResourceManagerService(new ModelStateWrapper(this.ModelState));
List<string> wl = pr.FetchWeeks(DateTime.Now.Year);
wl.Remove(week);
wl.Insert(0, week);
wl.Select(m => new SelectListItem { Text = m, Value = m });
ViewBag.Weeks = wl;
return View();
}
我从列表中删除的项目,并把它放在顶部,所以它由DDList显示。
EDIT2:
添加FetchWeeks
:
public List<string> FetchWeeks(int year)
{
List<string> weeks = new List<string>();
DateTime startDate = new DateTime(year, 1, 1);
startDate = startDate.AddDays(1 - (int)startDate.DayOfWeek);
DateTime endDate = startDate.AddDays(6);
while (startDate.Year < 1 + year)
{
weeks.Add(string.Format("From {0:dd/MM/yyyy} to {1:dd/MM/yyyy}", startDate, endDate));
startDate = startDate.AddDays(7);
endDate = endDate.AddDays(7);
}
return weeks;
}
EDIT3:由于kikyalex我们已经找到了解决办法:
当ViewBag属性具有相同的名称创建一个问题DDList阻止它改变它的价值。
我似乎仍然得到'无法将类型“使用System.Collections中选定的属性。 Generic.List'到'System.Collections.Generic.List '后检查并更改它,如你所说。 –
Christopher
你说得对。我忘了更改GET方法了。更新我的回答 –
没有更多的错误!但它仍然使我回到以前的日期。(不会更改为选定的一个)。 ViewBag.Weeks现在不包含选定的一个吗?编辑:我现在星期包含星期列表,但如何形式不会让DDList框中选定的一周? – Christopher