MVC模型验证 [英] MVC model validation

查看:235
本文介绍了MVC模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在构建一个需要用户模型验证的应用程序,如果不正确的属性被填写到用户中,它将会告诉他们。
我有数据注释设置,但我不知道我如何将错误消息传回给用户?
我已经设置了我的模型和视图。

So, im currently building an application that needs the user model validating, and if the incorrect properties are filled in to the user it will tell them. I have the data annotations set up, but im not sure how i relay the error message back to the user? I have this set up so far on my model and view.

模型

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上的文档,但我无法理解他们如何添加错误消息,表单知道如何向用户显示错误。

I believe the model needs to be passed back to the view in order to display the error message, and although i have read through the documentation on asp.net i cannot understand how they just add the error message and the form knows how to display the errors to the user.

我非常困惑。

推荐答案

你需要使用您的控制器中的ModelState.IsValid 以及视图中的 @ Html.ValidationMessageFor(model => model.FirstName)

You need to use ModelState.IsValid in your Controller and also @Html.ValidationMessageFor(model => model.FirstName) in your view:

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);
    } 
}

有关更多信息 HERE

@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">
}



控制器:



Controller:

[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);
}

这篇关于MVC模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆