gpt4 book ai didi

c# - 如何在 mvc4 razor 中显示验证消息

转载 作者:太空狗 更新时间:2023-10-30 00:26:06 24 4
gpt4 key购买 nike

我是 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) 创建 View 模型,在结构上表示您要显示的信息。

修复你的 View 模型:

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

修正你的 Action (我在这里编造这个是为了说明一个观点):

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) 现在您可以在 View 中遍历用户并创建带有验证消息的适当字段。

我们将此 View 称为 ListOfUsers.cshtml。在 View 中包含您需要的任何其他内容,但改用 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) 创建一个操作来接收提交的更改。此操作会自动将提交的值绑定(bind)到 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);

}

关于c# - 如何在 mvc4 razor 中显示验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13248352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com