我想为List of Models创建一个编辑器,它在我的ViewModel类中作为属性存在。
ViewModel类:
public class FooManagementDetailViewModel : ViewModelBase
{
public List<FooPermissionModel> FooPermissions { get; set; }
模特课:
public class FooPermissionModel
{
public string Name { get; set; }
public string Reason { get; set; }
public bool Selected { get; set; }
}
EditorTemplate:
@model FooPermissionModel
<table>
<thead>
<tr>
<th>
Heading
</th>
<th>
Heading
</th>
<th>
Heading
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
@Html.TextBoxFor(x => x.Name, new { @readonly = "readonly" })
</td>
<td>
@Html.CheckBoxFor(x => x.Selected)
</td>
<td>
@Html.TextBoxFor(x => x.Reason)
</td>
</tr>
</tbody>
</table>
查看:
<fieldset>
<legend>FooBarTitle</legend>
<div>
@Html.EditorFor(x => x.FooPermissions)
</div>
</fieldset>
返回的是仅名称的单个div。根本没有结构。 我错过了什么?
谢谢!
答案 0 :(得分:2)
我有一种感觉,你可能没有正确指定你的模型名称,或者MVC找不到你的EditorTemplate。
请注意,此示例的模板位置为:〜/ Views / Shared / EditorTemplates / FooPermissionModel.cshtml
以下显示了EditorTemplate正确渲染:
型号:
public class FooPermissionModel
{
public string Name { get; set; }
public string Reason { get; set; }
public bool Selected { get; set; }
}
视图模型:
public class FooManagementDetailViewModel
{
public List<FooPermissionModel> FooPermissions { get; set; }
}
控制器:
public ActionResult Index()
{
var fakePerms = new List<FooPermissionModel> ()
{
new FooPermissionModel { Name = "Foo1", Reason = "Boo", Selected=true },
new FooPermissionModel { Name = "Bazz", Reason = "Tootsie", Selected=false }
};
var model = new FooManagementDetailViewModel();
model.FooPermissions = fakePerms;
return View(model);
}
查看:
@model StackExamples.Models.FooManagementDetailViewModel
<fieldset>
<legend>FooBarTitle</legend>
<div>
@Html.EditorFor(x => x.FooPermissions)
</div>
</fieldset>
EditorTemplate:
@model StackExamples.Models.FooPermissionModel
<table>
<thead>
<tr>
<th>
Heading
</th>
<th>
Heading
</th>
<th>
Heading
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
@Html.TextBoxFor(x => x.Name, new { @readonly = "readonly" })
</td>
<td>
@Html.CheckBoxFor(x => x.Selected)
</td>
<td>
@Html.TextBoxFor(x => x.Reason)
</td>
</tr>
</tbody>
</table>
答案 1 :(得分:1)
你的@model应该是FooManagementDetailViewModel然后你可以预先知道FooPermissions.Items将是FooPermissions对象
答案 2 :(得分:1)
尝试使用EditorForModel()
查看:
@model FooPermissionModel
@using (Html.BeginForm("bar", "foo"))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Edit</legend>
@Html.EditorForModel()
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
控制器:
public ActionResult Edit()
{
//get instance of model
// <CODE GOES HERE>
// then pass it in the return
return View(mymodelinstance);
}
使用正确的模板,它应该为您完成剩下的工作并将其放入表中。