在我的控制器中,我按如下方式设置了SelectedYear字段;
[Authorize(Roles = "Administrator, AdminAccounts")]
public ActionResult BankHoliday(int? id)
{
BankHolidayViewModel BankHolidayViewModel = new BankHolidayViewModel();
int year = DateTime.Now.Year;
if (id.HasValue)
year = id.GetValueOrDefault();
BankHolidayViewModel.SelectedYear = year;
BankHolidayViewModel.GetYearData(year);
return View(BankHolidayViewModel);
}
每当我单步执行代码时,返回语句中的SelectedYear值始终是正确的。在下面的Year DropDownList中,这是在DropDownList中设置所选项的Value字段;
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/AdminAccounts.master" Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.BankHolidayViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
BankHoliday
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="AdminAccountsContent" runat="server">
<h3>Bank Holiday Administration</h3>
<p>Select the year: <%: Html.DropDownListFor(model => model.SelectedYear, Model.YearList)%></p>
<script language="javascript" type="text/javascript">
$(function () {
$("#SelectedYear").change(function () {
var year = $("#SelectedYear").val();
$("#wholepage").load("/AdminAccounts/BankHoliday/" + year);
});
});
YearList定义如下;
public class BankHolidayViewModel
{
public IList<BankHolidayExtended> BankHolidays { get; set; }
public IList<BankHolidayYear> Years { get; set; }
public int SelectedYear = DateTime.Now.Year;
public IEnumerable<SelectListItem> YearList
{
get
{
return this.Years.Select(item => new SelectListItem
{
Text = item.Year.ToString(),
Value = item.Year.ToString()
});
}
}
出于某种原因,在呈现视图时,下拉列表中没有选定的项目。我该如何解决这个问题?
答案 0 :(得分:1)
您的“继承”需要继承您的ViewModel。
Inherits="System.Web.Mvc.ViewPage<ViewModels.BankHolidayViewModel>"
创建YearList时,还需要设置所选值。像
这样的东西 YearList = new SelectList(GetYears(), "year", "year", SelectedYear);
修改的 在您的视图中,您可以设置所选值:
<%= Html.DropDownListFor(x => x.SelectedYear, new SelectList(Model.YearList, "Value", "Text", Model.SelectedYear))%>
或者你可以在我最初设置年份列表时执行此操作。 GetYears()将返回列表的年份。
public SelectList YearList { get; private set; }
public class BankHolidayViewModel(int year)
{
YearList = new SelectList(GetYears(), "Value", "Text", year);
然后返回视图
return View(new BankHolidayViewModel(year));
答案 1 :(得分:1)
我真的不想将我的对象更改为SelectList,尽管我确信这会有效。 相反,我通过改变吸气剂得到了答案;
public IEnumerable<SelectListItem> YearList
{
get
{
return this.Years.Select(item => new SelectListItem
{
Text = item.Year.ToString(),
Value = item.Year.ToString(),
Selected = item.Year == this.SelectedYear
});
}
}