0
這是我們如何實施級聯下拉式的年和月。選擇年/月後,表格被提交。當提交後查看時,所選年份值將保留(因爲我們在模型中已經處理了該值),但所選月份值不會保留。需要做什麼來堅持價值?如何在表單發佈後綁定月份下拉值?
型號
public class MyViewModel
{
public int? Year { get; set; }
public int? Month { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable.Range(2000, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
控制器
的HTTPGET和HttpPost行動,
//
// GET: /MenuSix/
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
public ActionResult Months(int year)
{
if (year == 2011)
{
return Json(
Enumerable.Range(1, 3).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
return Json(
Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
//
// POST: /MenuSix/
[HttpPost]
public ActionResult Index(MyViewModel myViewModel)
{
var month = myViewModel.Month; //11
var year = myViewModel.Year; //2011
return View(myViewModel);
}
查看
需要更改此處以保留月份值「Enumerable.Empty()」?
@model DemoWeb.Models.MenuSix.MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.Year, new SelectList(Model.Years, "Value", "Text"), "-- select year --")
@Html.DropDownListFor(x => x.Month, Enumerable.Empty<SelectListItem>(), "-- select month --")
<div align="center">
<input type="submit" id="valSubmit" value="Save"/>
</div>
}
@section PageScriptsAndCSS{
<script type="text/javascript">
$(document).ready(function() {
$('#Year').change(function() {
debugger;
var selectedYear = $(this).val();
if (selectedYear != null && selectedYear != '') {
$.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) {
var monthsSelect = $('#Month');
monthsSelect.empty();
$.each(months, function (index, month) {
monthsSelect.append($('<option/>', {
value: month.value,
text: month.text
}));
});
});
}
});
});
</script>
}
我想我們需要改變,@ Html.DropDownListFor(x => x.Month,Enumerable.Empty(),「 - select month - 」) –
user584018
但我想要空白組合月首先得到行動.... – user584018