如何显示mvc4剃刀验证消息(How to show validation message in m

2019-07-03 14:24发布

我在MVC剃刀新手,我要实现对文本框验证消息。 在这里,我动态创建文本框的一些如下:

查看代码:

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


}

在模块中我写的代码进行验证,如下所示:

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


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

现在,当已创建的所有文本框和当一个验证消息被显示为第一循环迭代文本框那么它将在另一文本框的前面太其上第二循环迭代创建自动显示。

请告诉我怎么回事错了。

Answer 1:

问题是,因为你使用的表达TextBoxForValidationMessageFor ,这是使用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; }
}

修正你的动作(我在做这件事在这里想说明一个观点):

public ActionResult ListOfUsers()
{
     var users = GetUserDataRows(); // gets your collection of DataRows
     var model = new ListOfUsersViewModel
                     {
                         UsersOfList = users.Select(row = new UserViewModel { UserName = row["FirstName"], LoginName = row["UserName"] }).ToList()
                     };

     return View(model);                  
}

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

这将导致HTML这样每个项目( 0的名称和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>

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

}


文章来源: How to show validation message in mvc4 razor