したがって、かなり単純な要件があります。ユーザー モデルの編集ページを許可しようとしていますが、ユーザー モデルは基本的に指示する 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; }
}
それらは私のモデルです。これらはデータベースから取得されるため、コントローラーで可能なすべての UserTypeModels のリストを作成し、実際の UserModel と共にビューに送信します。以下のコントローラーコードを参照してください。
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 を取得しています (これにより、正しい UserTypeModel にすべての属性 id/name/description も入力されます)。次に、考えられるすべての 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>
}
ご覧のとおり、「UserType_Id」の ID/名前で DDL を作成し、ViewBag.UserTypesList からリストを引き出しています。理想的には、私がしたいことは次のとおりです。
- SelectedValue が最初から正しく設定されていません。私はこれに関する多くの問題を読みましたが、私の解決方法はまだわかりません。これにリストが正しく事前入力されるようにしたいと思います。
- ユーザーが DDL の SelectedValue を変更すると、Model を Controller に戻し、Model.UserType.Id に正しいプロパティを設定したいのですが、Model.UserType が null として返されます。
編集の投稿のコードをわざわざ投稿するつもりはありません。パラメーターが次のとおりであることを知っておいてください。
[HttpPost]
public ActionResult Edit(UserModel pUserModel)