我有一个下拉列表,可以在更改所选值时重新加载页面。这可以按预期工作和渲染。唯一的问题是下拉列表返回默认值。如何更改默认值以匹配ViewBag.Value?
@Html.DropDownListFor(model => model.LevelId,
(
from choice in
(from p in Model.Defaults
group p by new { p.LevelId, p.LevelDescription } into c
select new { c.Key.LevelId, c.Key.LevelDescription })
select new SelectListItem
{
Text = choice.LevelDescription,
Value = choice.LevelId.ToString(),
Selected = false
}))
的JScript
$("#LevelId").change(function() {
var clientId = @Model.ClientId;
var compareDate = $("#EffectiveDate").val();
var level = $(this).val();
var params = $.param({ clientId: clientId, compareDate: compareDate, level : level });
var link = '@Url.Action("Create", "Choices")'; //"\\Choices\\RefreshView";
var url = link + "?" + params;
document.location = url;
});
控制器根据
中传递的参数设置ViewBag.Level答案 0 :(得分:1)
您可以在视图模型中添加一个属性IEnumerable<SelectListItem>
,您将在控制器中初始化该属性。然后将LevelId属性设置为您要预选的值:
public ActionResult Foo(string level)
{
var model = new MyViewModel();
var values = from choice in
(from p in Model.Defaults
group p by new { p.LevelId, p.LevelDescription } into c
select new { c.Key.LevelId, c.Key.LevelDescription })
select new {
Text = choice.LevelDescription,
Value = choice.LevelId.ToString()
}
);
model.Items = new SelectList(values, "Text", "Value");
model.LevelId = level;
return View(model);
}
然后在你看来:
@Html.DropDownListFor(model => model.LevelId, Model.Items)