Jus*_*ore 5 c# .net-4.0 visual-studio-2010 mvc-editor-templates asp.net-mvc-3
如何将下拉列表显示为编辑器模板的一部分?
所以我有一个Users实体和一个Roles实体.角色作为SelectList和User传递给视图,也就是用户.SelectList变为下拉列表,选择了正确的ID,所有内容都归功于此示例.
我正在尝试使用MVC 3为我的实体获得一个一体化的完美捆绑的EditorTemplate,这样我就可以调用EditorForModel,只要我有像Roles这样的外键,就可以通过下拉列表得到很好的字段. ,在这个特殊的例子中.
我的EditorTemlates\User.cshtml(基于ViewData动态生成布局):
<table style="width: 100%;">
@{
int i = 0;
int numOfColumns = 3;
foreach (var prop in ViewData.ModelMetadata.Properties
.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)))
{
if (prop.HideSurroundingHtml)
{
@Html.Display(prop.PropertyName)
}
else
{
if (i % numOfColumns == 0)
{
@Html.Raw("<tr>");
}
<td class="editor-label">
@Html.Label(prop.PropertyName)
</td>
<td class="editor-field">
@Html.Editor(prop.PropertyName)
<span class="error">@Html.ValidationMessage(prop.PropertyName,"*")</span>
</td>
if (i % numOfColumns == numOfColumns - 1)
{
@Html.Raw("</tr>");
}
i++;
}
}
}
</table>
Run Code Online (Sandbox Code Playgroud)
在视图上,我然后单独绑定SelectList,我想将其作为模板的一部分.
我的型号:
public class SecurityEditModel
{
[ScaffoldColumn(false)]
public SelectList roleList { get; set; }
public User currentUser { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的控制器:
public ViewResult Edit(int id)
{
User user = repository.Users.FirstOrDefault(c => c.ID == id);
var viewModel = new SecurityEditModel
{
currentUser = user,
roleList = new SelectList(repository.Roles.Where(r => r.Enabled == true).ToList(), "ID", "RoleName")
};
return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)
我的看法:
@model Nina.WebUI.Models.SecurityEditModel
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using(Html.BeginForm("Edit", "Security"))
{
@Html.EditorFor(m => m.currentUser)
<table style="width: 100%;">
<tr>
<td class="editor-label">
User Role:
</td>
<td class="editor-field">
<!-- I want to move this to the EditorTemplate -->
@Html.DropDownListFor(model => model.currentUser.RoleID, Model.roleList)
</td>
</tr>
</table>
<div class="editor-row">
<div class="editor-label">
</div>
<div class="editor-field">
</div>
</div>
<div class="editor-row"> </div>
<div style="text-align: center;">
<input type="submit" value="Save"/>
<input type="button" value="Cancel" onclick="location.href='@Url.Action("List", "Clients")'"/>
</div>
}
Run Code Online (Sandbox Code Playgroud)
希望这很清楚,让我知道你是否可以使用更多的澄清.提前致谢!
由于您需要访问 SelectList,因此您可以创建绑定到的编辑器模板SecurityEditModel,也可以在 ViewData 中传递 SelectList。就我个人而言,我会选择强类型方法。
| 归档时间: |
|
| 查看次数: |
1223 次 |
| 最近记录: |