私はVS2012RCをMVC4で使用しています。ボットはすべての目的と目的で、MVC3のふりをしてみましょう。親ビューとは異なるモデルを使用するフォームでPartialViewを処理する方法に関する標準のベストプラクティスを知りたいです。
たとえば、これは、使用可能なすべてのロールのテーブルを表示し、ユーザーがさらにロールを追加できるフォームを備えたビューです。
メインビュー-Roles.cshtml:
@model IEnumerable<RobotDog.Models.RoleModel>
<table>
@foreach(var role in Model) {
<tr>
<td class="roleRow">@role.Role</td>
</tr>
}
</table>
<div class="modal hide">
@Html.Partial("_AddRolePartial")
</div>
_AddRolePartial.cshtml
@model RobotDog.Models.RoleModel
@using(Html.BeginForm("AddRole","Admin", FormMethod.Post)) {
@Html.TextBoxFor(x => x.Role, new { @class = "input-xlarge", @placeholder = "Role"})
<input type="submit" value="Submit" class="btn btn-primary btn-large"/>
}
モデル:
public class RoleModel {
[Required]
[DataType(DataType.Text)]
[Display(Name = "Role")]
public string Role { get; set; }
}
ビューのコントローラー:
public ActionResult Roles() {
var model = from r in System.Web.Security.Roles.GetAllRoles()
select new RoleModel {Role = r};
return View(model);
}
PartialViewのコントローラー:
[HttpPost]
public ActionResult AddRole(RoleModel model) {
try {
System.Web.Security.Roles.CreateRole(model.Role);
RedirectToAction("Roles");
} catch(Exception) {
ModelState.AddModelError("", "Role creation unsuccessful.");
}
return ????; // not sure how to pass ModelState back to partialView
}
保持するViewModelを作成することを考えましたが、このPartialViewを使用するたびに、ViewModelを作成しなくても、必要なことを実現するためのより合理的な方法があるようですRoleModel
。IEnumerable<RoleModel>