控制器:
public ActionResult New()
{
var viewModel = new ViewModel();
viewModel.AllUsers = **Run a Database Query to get all users**
return View(viewModel);
}
查看:
@using (Html.BeginForm("New", "Card", FormMethod.Post, new Dictionary<string, object>() { { "id", "cardForm" } }))
{
**Among other form fields***
<div class="control-group">
label class="control-label LabelStyle">
Assigned To
</label>
<div>
@Html.DropDownListFor(model => model.AssignedToIds, Model.AllProjectUsersList.ToSelectList(u => u.Id.ToString(), u => u.Text, u => u.Selected ), new { @class = "chosen", multiple = "multiple"})
</div>
</div>
}
<script>
var cardForm = $('#cardForm');
cardForm.submit();
</script>
控制器(后动作):
[HttpPost]
public ActionResult New(CardFormViewModel viewModel)
{
if (ModelState.IsValid)
{
//Do Something
}
return View(viewModel);
}
问题是,如果ModelState
无效,并且我使用View
返回viewModel
,则AllProjectUsersList
为空。因此,构建视图时会发生异常。当然,我可以通过再次运行数据库查询并填充AllProjectUsersList
来解决此问题。
有什么方法可以保留以前填充的AllProjectUsersList
或以其他方式避免数据库查询?