在控制器的帖子操作中保留非表单相关数据(例如下拉选项)

时间:2017-05-26 06:31:05

标签: razor asp.net-mvc-5 unobtrusive-validation

控制器:

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或以其他方式避免数据库查询?

0 个答案:

没有答案