【问题标题】:MVC model validationMVC 模型验证
【发布时间】:2017-09-23 13:33:15
【问题描述】:

所以,我目前正在构建一个需要用户模型验证的应用程序,如果向用户填写了不正确的属性,它会告诉他们。 我已经设置了数据注释,但我不确定如何将错误消息转发给用户? 到目前为止,我已经在我的模型和视图上设置了这个。

模型

public class DatabaseModel
    {
        [Required(ErrorMessage = ("A first name is required"))]
        public string FirstName { get; set; }
        [Required(ErrorMessage = ("A last name is required"))]
        public string LastName { get; set; }
        [Required(ErrorMessage = ("A valid role is required"))]
        public string Role { get; set; }
        // TODO - Validate rank to only b 1 - 10
        //
        [Range(1,10, ErrorMessage = ("A rank between 1 and 10 is required"))]
        public int Rank { get; set; }      

    }

查看

@model RoleCreatorAndEditor.Models.DatabaseModel
@{
    ViewData["Title"] = "Index";
}

<h2>User Information</h2>

<p>This is your user information!</p>

@using (Html.BeginForm("Index", "Home", FormMethod.Post)) {
    @Html.Label("First Name")
    <br>
    @Html.TextBoxFor(m => m.FirstName)
    <br>
    @Html.Label("Last Name")
    <br>
    @Html.TextBoxFor(m=>m.LastName)
    <br>
    @Html.Label("Role")
    <br>
    @Html.TextBoxFor(m => m.Role)
    <br>
    @Html.Label("Rank")
    <br>
    @Html.TextBoxFor(m => m.Rank)
    <br><br>
    <input type="submit" value="Save">
}

我的控制器

public class HomeController : Controller
    {
        // GET: Home
        [HttpGet]
        public ActionResult Index()
        {
            DatabaseModel model = new DatabaseModel();
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(DatabaseModel model)
        {
            if (ModelState.IsValid)
            {
                ListToDatatable convert = new ListToDatatable();
                DataTable user = convert.Convert(model);
                DatabaseRepository dbRepo = new DatabaseRepository();
                dbRepo.Upload(user);
            }
            return View();
        }
    }

我相信模型需要传递回视图才能显示错误消息,虽然我已经阅读了 asp.net 上的文档,但我无法理解他们如何添加错误消息,而表单知道如何向用户显示错误。

我非常困惑。

【问题讨论】:

  • 你的控制器在哪里?
  • 在视图中包含@Html.ValidationMessageFor(m =&gt; m.FirstName)等(并包含客户端验证的相关脚本。在控制器中您还需要if(!ModelState.IsValid) { return View(model); }
  • 现在更新问题
  • 这张票可能重复。 stackoverflow.com/questions/5739362/…
  • @karman 我不明白该票的答案,也不明白如何在我自己的问题上使用它

标签: asp.net-mvc error-handling model


【解决方案1】:

您需要在 Controller 中使用 ModelState.IsValid 并在视图中使用 @Html.ValidationMessageFor(model =&gt; model.FirstName)

public ActionResult Index(ViewModel _Model) 
{ 
    // Checking whether the Form posted is valid one. 
    if(ModelState.IsValid) 
    { 
        // your model is valid here.
        // perform any actions you need to, like database actions,
        // and/or redirecting to other controllers and actions.
    }
    else 
    {
        // redirect to same action
        return View(_Model);
    } 
}

你的例子:

@model RoleCreatorAndEditor.Models.DatabaseModel
@{
    ViewData["Title"] = "Index";
}

<h2>User Information</h2>

<p>This is your user information!</p>
@using (Html.BeginForm("Index", "Home", FormMethod.Post)) {
    @Html.LabelFor(m=>m.FirstName)
    <br>
    @Html.TextBoxFor(m => m.FirstName)
    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })

    <br>
    @Html.LabelFor(m=>m.LastName)
    <br>
    @Html.TextBoxFor(m=>m.LastName)
    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

    . . .

    <input type="submit" value="Save">
}

控制器:

[HttpPost]
public ActionResult Index(DatabaseModel model)
{
    if (ModelState.IsValid)
    {
        ListToDatatable convert = new ListToDatatable();
        DataTable user = convert.Convert(model);
        DatabaseRepository dbRepo = new DatabaseRepository();
        dbRepo.Upload(user);
    }
    return View(model);
}

【讨论】:

  • 对不起,我忘记了控制器的代码,我现在更新我的问题。
  • 所以我将模型传递到我的 ccontrolr,并且我有 IsValid,但在此之后我感到困惑
  • 如果不包括视图中每个属性的相关@Html.ValidationMessageFor() 就不太好了 :)
  • @StephenMuecke 所以@html.validationMessageFor(),我到底如何使用它?我为所有的问题道歉,我以前从未处理过 MVC。
  • @Ryanwhite - 请参阅我对您的问题的评论 - 每个属性只需要一个(并使用 @Html.LabelFor(m =&gt; m.FirstName) 而不是 Label())并使用 return View(model); - 始终传递模型
猜你喜欢
  • 2015-02-26
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多