gpt4 book ai didi

asp.net-mvc-2 - MVC DropDownListFor - 验证失败后我必须手动重新填充选项吗?

转载 作者:行者123 更新时间:2023-12-04 11:15:47 24 4
gpt4 key购买 nike

我有一个包含几个属性的 View 模型类。基本上,当前记录(用户正在编辑)和选项列表(用于使用 DropDownListFor 填充下拉列表)。

提交表单后,如果模型状态无效,我将返回 View 。我了解该表单是使用来自 ModelState["name"].Value.AttemptedValue 的“拒绝”输入填充的。 ,但我不确定如何处理下拉列表的值列表。

如果我什么都不做,在验证失败并返回页面时,我会收到“对象引用未设置为对象的实例”错误,因为 View 模型的列表属性为空。我知道它是空的,因为它没有从表单发布中绑定(bind),所以我可以在返回 View 之前从数据库中重新填充它。

这是正确的方法吗,还是我错过了一种更明显的方法来使下拉值持续存在?

最佳答案

是的,如果您打算在 POST 操作中返回相同的 View ,这是正确的方法:

  • 从数据库
  • 绑定(bind) GET 操作中的列表
  • 渲染 View
  • 用户将表单提交给 POST 操作
  • 在此操作中,您仅获取选定的值,因此如果模型无效并且您需要重新显示 View ,您需要从数据库中获取列表以填充您的 View 模型。

  • 以下是 MVC 中常用模式的示例:
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
    var model = new MyViewModel
    {
    Items = _repository.GetItems()
    };
    return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
    if (!ModelState.IsValid)
    {
    // Validation failed, fetch the list from the database
    // and redisplay the form
    model.Items = _repository.GetItems();
    return View(model);
    }
    // at this stage the model is valid =>
    // use the selected value from the dropdown
    _repository.DoSomething(model.SelectedValue);
    // You no longer need to fetch the list because
    // we are redirecting here
    return RedirectToAction("Success", "SomeOtherController");
    }
    }

    关于asp.net-mvc-2 - MVC DropDownListFor - 验证失败后我必须手动重新填充选项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4178303/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com