C# 如何在 mvc4 razor 中显示验证消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13248352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show validation message in mvc4 razor
提问by Pravesh Singh
I am newbie in MVC Razor and I want to implement validation message on textboxes. Here I'm creating some textbox dynamically as follows:
我是 MVC Razor 的新手,我想在文本框上实现验证消息。在这里,我正在动态创建一些文本框,如下所示:
View 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" })
}
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.
请告诉我出了什么问题。
回答by moribvndvs
The problem is because the expression you're using in TextBoxForand 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.
问题是因为您在TextBoxForand 中使用的表达式ValidationMessageFor(MVC 使用它为字段创建字符串名称并从 中查找验证消息)ModelState在整个循环迭代中始终相同。
Your approach here seems a bit flawed, so my answer is more comprehensive.
你在这里的方法似乎有点缺陷,所以我的回答更全面。
1) Make view models that structurally represent the info you are trying to display.
1)制作在结构上代表您试图显示的信息的视图模型。
Fix your view models:
修复您的视图模型:
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) Now you can iterate through users in your view and create proper fields with validation messages.
2) 现在您可以在您的视图中遍历用户并使用验证消息创建适当的字段。
Let's call this view ListOfUsers.cshtml. Include whatever other things you need in your view, but use a forloop instead.
让我们称之为视图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>
}
This will result in HTML like this for each item (0in the name and id will be the index of the user in the collection):
这将导致每个项目的 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) Create an action to receive submitted changes. This action will automatically bind the submitted values to the modelargument, and do validation for you. All you need to do is check ModelState.IsValid.
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);
}

