我正在尝试制作一个编辑预定义模型列表的视图。因此,它是一个以模型列表为参数的强类型视图。我使用自定义 Html 助手来编辑各个模型。Get 视图显示正确,但后发视图模型(模型列表)始终为空。我知道这里有很多关于这个话题的问题,但我已经尝试了 2 天了。
这是基本模型:
public class PrivacyManagerModel
{
[Required]
[Display(Name="Privacy Type Id")]
public int PrivaceTypeId { get; set; }
[Required]
[Display(Name = "Visibility Level Id")]
public int VisibilityLevelId { get; set; }
}
以下是控制器操作:
//GET: /Profile/ManagePrivacy
[Authorize]
public ActionResult ManagePrivacy()
{
PrivacyTypeService _privacyTypeService=new PrivacyTypeService();
IEnumerable<PrivacyFlagType> privacyTypes = _privacyTypeService.GetPrivacyFlagTypes();
List<PrivacyManagerModel> model=new List<PrivacyManagerModel>();
foreach (PrivacyFlagType type in privacyTypes)
{
PrivacyManagerModel temp=new PrivacyManagerModel();
temp.PrivaceTypeId=type.PrivacyFlagTypeId;
model.Add(temp);
}
ViewBag.privacyTypes=privacyTypes;
return View(model);
}
//POST: /Profile/ManagePrivacy
[Authorize]
[HttpPost]
public ActionResult ManagePrivacy(IEnumerable<PrivacyManagerModel> model)
{
if (ModelState.IsValid)
{
do stuff
}
else
{
return View(model);
}
}
这是试图编辑列表的视图PrivacyManagerModel
:
@model IEnumerable<Klever.PrivacyManagerModel>
@using Klever
@{
ViewBag.Title = "ManagePrivacy";
var _privacyTypes = ViewBag.privacyTypes as IEnumerable<PrivacyFlagType>;
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
@foreach(PrivacyManagerModel item in Model)
{
<div class="display-label">
@Html.DisplayFor(modelItem=>item.PrivaceTypeId)
</div>
<div class="editor-field">
@Html.EditorFor(modelItem=>item)
</div>
}
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
最后是 Html 助手 EditTemplate PrivacyManagerModel
:
@model Klever.PrivacyManagerModel
@using Klever.Components
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@{
PrivacyTypeService _privacyService = new PrivacyTypeService();
var visibilityLevels=_privacyService.GetVisibilityLevels();
}
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.PrivaceTypeId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model=>model.VisibilityLevelId,new SelectList(visibilityLevels,"VisibilityLevelId","Name"))
@Html.ValidationMessageFor(model => model.VisibilityLevelId)
</div>
</fieldset>
同样,GET 操作工作正常(它正确显示视图),但 Post 操作始终接收 Null 模型作为参数。非常感谢您的帮助。谢谢