私はユーザー管理用のユーザーコントローラーを持っており、ユーザーが編集ページからサブミットするときにドロップダウン選択肢を取得する方法を理解しようとしています。私がページ上でsubmitを押すたびに、ビューモデルの値のどれも投稿に通じていないようです。私は、彼らが役割を設定するためにドロップダウンから選択した価値を得ることができません。以下View Modelのドロップダウンから送信されたデータを取得しますか?
public class PersonViewModel
{
public int PersonId { get; set; }
[Display(Name = "Full Name")]
public string FullName { get; set; }
public string Email { get; set; }
[Display(Name = "Current Role")]
public string SetRole { get; set; }
public List<RoleListViewModel> Roles { get; set; }
}
参照コントローラの編集機能:以下
参照ビューモデルここ
// GET: People/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.people.Find(id);
if (person == null)
{
return HttpNotFound();
}
PersonViewModel pvm = new PersonViewModel();
List<IdentityRole> roles = adb.Roles.ToList();
var rlvm = new List<RoleListViewModel>();
roles.ForEach(x => rlvm.Add(new RoleListViewModel { RoleId = x.Id, RoleName = x.Name }));
pvm.PersonId = person.PersonId;
pvm.FullName = person.FirstName + " " + person.LastName;
pvm.Email = person.Email;
pvm.Roles = rlvm;
ViewBag.RoleList = new SelectList(rlvm, "RoleName", "RoleName", person.CurrentRole);
return View(pvm);
}
// POST: People/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonViewModel pvm)
{
if (ModelState.IsValid)
{
db.Entry(pvm).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
var usr = new AccountController();
var pers = db.people.Where(x => x.PersonId == pvm.PersonId).FirstOrDefault();
usr.UserManager.AddToRoleAsync(pers.NetId, /* their choice should go here but how? */);
db.SaveChanges();
return View(pvm);
}
はCSHTMLです:
<div class="form-group">
@Html.LabelFor(model => model.Roles, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="form-control-static">
@Html.DropDownList("RoleList", null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Roles, "", new { @class = "text-danger" })
</div>
</div>
あなたのモデルに存在しない 'RoleList'という名前のプロパティへのバインディング。 @Html.DropDownListFor(m => m.SetRole、(SelectList)、ViewBag.RoleList) 'そして' SelectList'コンストラクタの最後のパラメータを削除する必要があります(オプションを選択したい場合は'SetRole'の値を設定する必要があります)。そしてあなたはラベルと検証メッセージが 'Roles'ではなく' SetRole'に束縛されるべきです。ビューモデルを持っているので、 'Roles'は' Enumerable 'の型で' VIewBag'を取り除かなければなりません。 –
私はコード[ここ]を勉強することをお勧めします(http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but -must-be-o) –