gpt4 book ai didi

asp.net-mvc-3 - asp.net MVC 模型如何生成输入名称?

转载 作者:行者123 更新时间:2023-12-01 13:13:29 24 4
gpt4 key购买 nike

在带有 Razor 标记的 MVC 中的 EditorFor View 中,如果您这样做:

@Html.TextBox("")

HTML 输出模型的正确输入名称,如下所示:

<input id="usr_Roles" name="usr.Roles" type="text" value="">

“usr.Roles”名称来自此 EditorFor 行:

@Html.EditorFor(modelItem => usr.Roles, "RoleList") 

不幸的是,我正在尝试生成一组名为“usr.Roles”的复选框。由于 MVC 呈现复选框的方式,我无法使用 Html.Checkbox。我可以像这样手动生成它们:

@foreach (string roleName in Roles.GetAllRoles())
{
string checkboxId = "checkbox_" + roleName;
<input type="checkbox" name="usr.Roles" id="@checkboxId" value="@roleName" @Html.Raw(Model.Contains(roleName) ? "checked" : "") />
<label for="@checkboxId">@roleName</label>
}

上面的工作,但只是因为我手动指定“usr.Roles”作为复选框名称。

我的问题是:在对象和属性的迷宫中,@Html.TextBox 对象在哪里找到“usr.Roles”“usr-Roles”字符串?我可以自己找到它并在复选框中使用它吗?

最佳答案

我不知道为什么你会想要手动生成你的复选框的 ID 和名称,而不是简单地使用 Html.CheckBoxFor 助手来为你做这一切,但以防万一你有一些理由,方法如下:

@{
var name = ViewData.TemplateInfo.GetFullHtmlFieldName("");
}

@foreach (string roleName in Roles.GetAllRoles())
{
string checkboxId = "checkbox_" + roleName;
<input type="checkbox" name="@name" id="@checkboxId" value="@roleName" @Html.Raw(Model.Contains(roleName) ? "checked" : "") />
<label for="@checkboxId">@roleName</label>
}

显然,此处显示的内容纯粹出于某些教育目的。我真的会避免这种怪事,而只是使用 Html 帮助程序和编辑器模板。在您看来,令我震惊的另一件事是以下代码行:Roles.GetAllRoles()。就好像您的 View 正在查询数据一样。这是 View 应该做的最后一件事。 Controller 负责查询数据、填充 View 模型并将此 View 模型传递给 View ,以便它仅显示数据。

那么让我们尝试详细说明您的示例。据我所知,您正在尝试显示每个角色的复选框列表,以便用户可以选择它们。

一如既往,您从表达 View 需求的 View 模型开始:

public class MyViewModel
{
public IEnumerable<RoleViewModel> Roles { get; set; }
}

public class RoleViewModel
{
public string RoleName { get; set; }
public bool Selected { get; set; }
}

然后您编写一个 Controller 操作,它将查询您的数据并填充 View 模型:

public ActionResult Index()
{
var roles = Roles.GetAllRoles();
var model = new MyViewModel
{
Roles = roles.Select(role => new RoleViewModel
{
RoleName = role,
Selected = ??????
})
};
return View(model);
}

然后你会有一个Index.cshtml View :

@model MyViewModel
@Html.EditorFor(x => x.Roles)

以及将为 Roles 集合的每个元素呈现的相应编辑器模板 (~/View/Shared/EditorTemplates/RoleViewModel.cshtml):

@model RoleViewModel
@Html.CheckBoxFor(x => x.Selected)
@Html.LabelFor(x => x.Selected, Model.RoleName)

View 中不再有 foreach 循环,不再使用名称和 ID 进行丑陋的修改,不再从 View 中提取数据。

关于asp.net-mvc-3 - asp.net MVC 模型如何生成输入名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6749189/

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