[英]ASP.NET MVC render View and retain values when validation fails on a dynamically generated View
[英]Retain a list of objects and pass it to the create/edit view when validation fails in ASP.NET MVC 2
我在模型中綁定了外鍵屬性。 我正在模型中傳遞該屬性的可能值列表。 該模型如下所示:
public class UserModel
{
public bool Email { get; set; }
public bool Name { get; set; }
public RoleModel Role { get; set; }
public IList<RoleModel> Roles { get; set; }
}
public class RoleModel
{
public string RoleName
{
get;
set;
}
}
這是我在控制器中的功能:
public ActionResult Create()
{
IList<RoleModel> roles = RoleModel.FromArray(_userService.GetAllRoles());
UserModel model = new UserModel()
{
Roles = roles
};
return View(model);
}
我認為:
<div class="editor-label">
<%= Html.LabelFor(model => model.Role) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.Role, new SelectList(Model.Roles, "RoleName", "RoleName", Model.Role))%>
<%= Html.ValidationMessageFor(model => model.Role)%>
</div>
驗證失敗后,我該怎么做才能將角色列表返回給我的控制器,以將其再次傳遞給視圖。 這就是我需要的:
[HttpPost]
public ActionResult Create(UserModel model)
{
if (ModelState.IsValid)
{
// insert logic here
}
//the validation fails so I pass the model again to the view for user to update data but model.Roles is null :(
return View(model);
}
如上面的注釋中所述,我需要將帶有角色列表的模型再次傳遞給我的視圖,但是model.Roles
為null
。 目前,我再次向服務請求角色( model.Roles = RoleModel.FromArray(_userService.GetAllRoles());
),但是我不想增加從數據庫獲取列表的額外開銷。 。
有人知道該怎么做嗎?
您可以將其存儲在TempData中。
TempData["UserRoles"] = Model.Roles;
也就是說,我傾向於避開在兩次請求之間保留數據。 認真地問自己,回到數據庫將耗費多少精力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.