我正在運行asp.net 4 mvc,並且我創建了默認爲列表中第一個條目的日期的DropDownList。當我選擇一個條目時,我調用一個控制器函數並做一些處理。但是,當我的頁面進行回發時,不是顯示我選擇的列表項目,而是再次顯示原始默認列表項目。DropDownList未設置選定的值
如何讓我的頁面顯示我從列表中選擇的最後一個項目?我花了整整兩天的時間搜索這個網站和互聯網尋找解決方案,但我沒有嘗試似乎工作。任何援助將不勝感激。
我的HTML視圖
@Html.DropDownList("selectList", Model.ReverseMonthsLists(),
new { @onchange = "CallChangefunc(this.value)" })
<script>
function CallChangefunc(val) {
window.location.href = "/dashboard/Report_Performance?id=" + val;
}
</script>
我的視圖模型
public SelectList MonthList { get; set; }
public IEnumerable<SelectListItem> ReverseMonthsLists()
{
var selectListItems = GetDates()
.Select(_ => _.ToString("MMM yyyy"))
.Select((dateString, index) => new SelectListItem { Selected = index == 0, Text = dateString, Value = dateString })
.ToList();
return selectListItems;
}
public static IEnumerable<DateTime> GetDates()
{
DateTime startDate = new DateTime(2017, 6, 1).Date;
var currentDate = DateTime.Now.Date;
int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
var dates = new List<DateTime>(numberOfMonthsToShow);
currentDate = currentDate.AddMonths(-1);
for (int i = 0; i < numberOfMonthsToShow; i++)
{
dates.Add(currentDate);
currentDate = currentDate.AddMonths(-1);
}
return dates;
}
我的控制器
[RequireLogin]
public ActionResult Report_Performance(string id)
{
DateTime newDate = DateTime.Now.Date.AddMonths(-1);
if (id != null)
newDate = DateTime.Parse(id);
var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, newDate);
return this.View(aVar);
}
能告訴你的'GetStats'方法的代碼?我猜測它總是返回相同的數據,所以它會幫助我們看到底下發生了什麼。 – sleeyuen