簡體   English   中英

如何在mvc4 razor中顯示驗證消息

[英]How to show validation message in mvc4 razor

我是MVC Razor的新手,我想在文本框上實現驗證消息。 這里我動態創建一些文本框,如下所示:

查看代碼:

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

現在,當創建了所有文本框並且為第一個循環迭代文本框顯示一個驗證消息時,它將自動顯示在另一個文本框的前面,這是在第二個循環迭代中創建的。

請告訴我哪里出錯了。

問題是因為您在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);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM