【问题标题】:TextBoxFor default value and keep edited value after validation failTextBoxFor 默认值并在验证失败后保留编辑值
【发布时间】:2017-03-10 08:54:10
【问题描述】:

剃刀代码如:

@Html.TextBoxFor(Model => Model.Name, new { @Value = student.t_Name })

我在 Controller 中使用 .NET MVC 的模型验证,

    if (ModelState.IsValid)
    {
        return RedirectToAction("B");
    }
    else 
    {
        return View(); // when validation failed
    }

我的情况是我有一个编辑功能,例如: 原始数据:

birthday: 1992-05-26

编辑后:

birthday: 1992-05-32

在我将这个提交给Controller并进行模型验证后,它将验证失败,并返回上一个视图(表单提交之前的视图), 我要它显示

birthday:1992-05-32

而不是

birthday:1992-05-26

【问题讨论】:

  • 返回视图时添加模型到视图`return View(yourmodel);`
  • 你想只在生日字段中输入原始值吗?
  • 你能展示你的模型吗?
  • 在使用HtmlHelper 方法时切勿设置value 属性,除非您想确保绑定失败。在将模型传递给视图之前,在 GET 方法中设置属性值 - model.Name = student.t_Name
  • 删除所有的`new { value = ... }`属性,它会正常工作。

标签: c# .net asp.net-mvc razor


【解决方案1】:

您应该像这样设置控制器的 ViewModel 值:

public ActionResult YourControllerMethod(YourViewModel model)
{
    if (ModelState.IsValid)
    {
        return RedirectToAction("B");
    }
    else 
    {
        ViewData.Model = model; //where model is your controller model
        return View(); // when validation failed
    }
}

【讨论】:

    【解决方案2】:

    在返回 View 时,您需要将当前发布的模型实例传回给 view,例如:

    public ActionResult YourAction(SomeModel model)
    {
       if (ModelState.IsValid)
       {
         return RedirectToAction("B");
       }
       else 
       {
        return View(model);
       }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多