C# 如何在mvc4中显示验证消息

C# 如何在mvc4中显示验证消息,c#,asp.net-mvc,razor,asp.net-mvc-4,validation,C#,Asp.net Mvc,Razor,Asp.net Mvc 4,Validation,我是MVC Razor的新手,我想在文本框上实现验证消息。在这里,我将动态创建一些文本框,如下所示: [Required (ErrorMessage="*")] public string UsernameOfLoginInfoTab { get; set; } [Required(ErrorMessage = "*")] public string LoginNameOfLoginInfoTab {

我是MVC Razor的新手,我想在文本框上实现验证消息。在这里,我将动态创建一些文本框,如下所示:

[Required (ErrorMessage="*")]
    public string UsernameOfLoginInfoTab
    {
        get;
        set;
    }


   [Required(ErrorMessage = "*")]
    public string LoginNameOfLoginInfoTab
    {
        get;
        set;
    }
查看代码:

foreach (var items in (IEnumerable<System.Data.DataRow>)Model.UsersOfList)
{

  @Html.TextBoxFor(m => m.LoginNameOfLoginInfoTab, new { @class = "textBox_LoginInfoAndPermission", @value = (Model.LoginNameOfLoginInfoTab = items["UserName"].ToString()), @id = ("txtUserLoginName" + Model.UsernameOfLoginInfoTab.Trim()) })

  @Html.ValidationMessageFor(m => m.LoginNameOfLoginInfoTab, null, new { @class = "ErrorMessage" })

  @Html.TextBoxFor(m => m.UsernameOfLoginInfoTab, new { @class = "textBox_LoginInfoAndPermission", @value = (Model.UsernameOfLoginInfoTab = items["FirstName"].ToString()), @id = ("txtUserName" + Model.UsernameOfLoginInfoTab.Trim()) })

  @Html.ValidationMessageFor(m => m.UsernameOfLoginInfoTab, null, new { @class = "ErrorMessage" })


}
现在,当所有文本框都已创建,并且当第一个循环迭代文本框显示一条验证消息时,它也将自动显示在第二个循环迭代中创建的另一个文本框前面


请告诉我出了什么问题

问题是因为在
TextBoxFor
ValidationMessageFor
中使用的表达式在循环的整个迭代过程中始终是相同的,MVC使用该表达式为字段创建字符串名称并从
ModelState
查找验证消息

你的方法似乎有点缺陷,所以我的答案更全面

1) 制作在结构上表示您试图显示的信息的视图模型

修复视图模型:

public class UserInfoViewModel
{
    [Required (ErrorMessage="*")]
    public string UserName { get; set; }


   [Required(ErrorMessage = "*")]
    public string LoginName { get; set; }
}

// I don't know if you actually need this or not, but your existing model may contain additional properties relevant to the view that I don't know about, so I'll keep it.
public class ListOfUsersViewModel
{
    public IList<UserInfoViewModel> UsersOfList { get; set; }
}
2) 现在,您可以在视图中遍历用户,并使用验证消息创建适当的字段

我们将此视图称为
ListOfUsers.cshtml
。在视图中包含您需要的任何其他内容,但改用
for
循环

@using(Html.BeginForm("ListOfUsers"))
{
    <ul>
    @for (var i = 0; i < Model.UsersOfList.Count; i++)
    {
       <li>
       @Html.TextBoxFor(m.UsersOfList[i].LoginName, new {@class="textbox_LoginInfoAndPermission"})
       @Html.ValidationMessageFor(m => m.UsersOfList[i].LoginName)

       @Html.TextBoxFor(m.UsersOfList[i].UserName, new {@class="textbox_LoginInfoAndPermission"})
       @Html.ValidationMessageFor(m => m.UsersOfList[i].UserName)
       </li>
    }
    </ul>
   <button type="submit">Submit changes</button>
}
3) 创建一个操作以接收提交的更改。此操作将自动将提交的值绑定到
model
参数,并为您执行验证。您只需检查
ModelState.IsValid

[HttpPost, ActionName("ListOfUsers")]
public ActionResult ListOfUsersPost(ListOfUsersViewModel model)
{
    // at this point, model will be instantiated, complete with UsersOfList with values submitted by the user

    if (ModelState.IsValid) // check to see if any users are missing required fields. if not...
    {
         // save the submitted changes, then redirect to a success page or whatever, like I do below
        return RedirectToAction("UsersUpdated");
    }

    // if ModelState.IsValid is false, a required field or other validation failed. Just return the model and reuse the ListOfUsers view. Doing this will keep the values the user submitted, but also include the validation error messages so they can correct their errors and try submitting again
    return View("ListOfUsers", model);

}

您可以在视图中使用foreach循环,而不是for循环。这将消除每次访问用户时都需要索引的需要(即,您将使用user.UserName而不是m.UsersOfList[i].UserName)。@rouan您需要索引器,以便MVC
TextBoxFor
ValidationMessageFor
助手将为模型绑定和模型状态生成正确的HTML元素ID/名称(分别)。
<li>
<input type="text" id="UsersOfList_0_LoginName" name="UsersOfList[0].LoginName" value="..." />
<span class="field-validation-valid" data-valmsg-for="UsersOfList_0_LoginName" ... ></span>

<input type="text" id="UsersOfList_0_UserName" name="UsersOfList[0].UserName" value="..." />
<span class="field-validation-valid" data-valmsg-for="UsersOfList_0_UserName" ... ></span>
</li>
[HttpPost, ActionName("ListOfUsers")]
public ActionResult ListOfUsersPost(ListOfUsersViewModel model)
{
    // at this point, model will be instantiated, complete with UsersOfList with values submitted by the user

    if (ModelState.IsValid) // check to see if any users are missing required fields. if not...
    {
         // save the submitted changes, then redirect to a success page or whatever, like I do below
        return RedirectToAction("UsersUpdated");
    }

    // if ModelState.IsValid is false, a required field or other validation failed. Just return the model and reuse the ListOfUsers view. Doing this will keep the values the user submitted, but also include the validation error messages so they can correct their errors and try submitting again
    return View("ListOfUsers", model);

}