所以我有一个非常简单的要求。我正在尝试允许我的用户模型的编辑页面,但用户模型引用了基本上指示的UserTypeModel(Admin / Regular / Super / etc)。我正在尝试在编辑视图中填充一个组合框,以选择它们应该是什么用户类型。请参阅下面的代码:
public class UserModel : BaseModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public UserTypeModel UserType { get; set; }
}
public class UserTypeModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
这些是我的模特。这些是从数据库中获取的,因此在我的Controller中,我创建了一个包含所有可能的UserTypeModel的List,并将它们与实际的UserModel一起发送到View。请参阅以下控制器代码:
public ActionResult Edit(int pId = 0)
{
UserModel vUserModel = fMySqlService.GetUser(pId);
List<UserTypeModel> vUserTypes = new List<UserTypeModel>(fMySqlService.GetAllUserTypes());
SelectList vSelectList = new SelectList(vUserTypes, "Id", "Name", vUserModel.UserType);
ViewBag.UserTypesList = vSelectList;
return View(vUserModel);
}
正如您在上面所看到的,我正在获取要编辑的特定UserModel(这也会填充具有所有属性id / name / description的正确UserTypeModel)。然后,我创建一个包含所有可能的UserTypeModel的列表,并通过ViewBag发送它。
现在为最后一部分编辑查看代码。我认为这是我最吮吸的地方......
@model Project.Models.UserModel
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>UserModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Phone)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Phone)
@Html.ValidationMessageFor(model => model.Phone)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.UserType.Name)
</div>
<div class="editor-field">
@Html.DropDownList("UserType_Id", ViewBag.UserTypesList as SelectList)
</div>
@Html.HiddenFor(model => model.Id)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
因此,您可以看到我正在创建一个ID /名称为“UserType_Id”的DDL,并从ViewBag.UserTypesList中拉出我的列表。理想情况下,我想要发生的是:
我不打算发布编辑帖子的代码,只知道参数是:
[HttpPost]
public ActionResult Edit(UserModel pUserModel)