如何显示在mvc4剃刀验证消息 [英] How to show validation message in mvc4 razor

查看:99
本文介绍了如何显示在mvc4剃刀验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am newbie in MVC Razor and I want to implement validation message on textboxes. Here I'm creating some textbox dynamically as follows:

查看code:

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


}

在模块中我写code进行验证如下:

in the module I've written code for validation as follows:

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


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

现在当已创建的所有文本框和当一个验证消息正在显示的第一个循环迭代文本框,然后它会在另一个文本框的太前面这是在第二循环迭代创建自动显示。

Now when all textboxes has been created and when one validation message is displaying for first loop iteration textbox then it will automatically displaying in front of another textbox too which is created on second loop iteration.

请告诉我怎么回事错了。

Please tell me whats going wrong.

推荐答案

问题是因为您使用的是 TextBoxFor 除权pression和 ValidationMessageFor ,用于通过MVC为现场创建一个字符串名称,并从的ModelState ,始终是相同的在整个循环的迭代

The problem is because the expression you're using in TextBoxFor and ValidationMessageFor, which is used by MVC to create a string name for the field and look up validation messages from ModelState, is always the same throughout the iteration of the loop.

您的方式在这里似乎有点瑕疵,所以我的答案是多个COM prehensive。

Your approach here seems a bit flawed, so my answer is more comprehensive.

1)请查看模型结构重新present您要显示的信息。

1) Make view models that structurally represent the info you are trying to display.

解决您的视图模型:

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

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

Fix your action (I'm making this up here to illustrate a point):

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)现在,你可以通过你的观点的用户重复和验证消息创造适宜的领域。

2) Now you can iterate through users in your view and create proper fields with validation messages.

让我们把这个观点 ListOfUsers.cshtml 。包括您在您的视图所需要的任何其他东西,但使用循环来代替。

Let's call this view ListOfUsers.cshtml. Include whatever other things you need in your view, but use a for loop instead.

@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将是用户的集合中的指数):

This will result in HTML like this for each item (0 in the name and id will be the index of the user in the collection):

<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)创建一个动作来接收提交的变化。此操作将提交的数据自动绑定到模式参数,并为你做验证。所有你需要做的是检查 ModelState.IsValid

3) Create an action to receive submitted changes. This action will automatically bind the submitted values to the model argument, and do validation for you. All you need to do is check 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);

}

这篇关于如何显示在mvc4剃刀验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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