这是我的观点模型:
public class AccEditViewModel
{
[Required]
public int Id { get; set; }
[Required]
[Display(Name = "Branch")]
public List<long> Branches { get; set; }
[Required]
[Display(Name = "User Type")]
public string UserType { get; set; }
[Required]
[Display(Name = "IsActive")]
public bool IsActive { get; set; }
}
这是我在控制器中的动作方法:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser user = UserManager.FindById((int)id);
if (user == null)
{
return HttpNotFound();
}
ApplicationDbContext db = new ApplicationDbContext();
AccEditViewModel model = new AccEditViewModel()
{
Id = user.Id,
IsActive = user.IsActive,
UserType = user.UserType,
};
model.Branches = new List<long>();
foreach (Branch branch in user.Branches)
{
model.Branches.Add(branch.BranchID);
}
ViewBag.Branches = db.Branches.Where(x => x.IsActive == true).AsEnumerable();
ViewBag.UserTypes = new SelectList(UserTypes.GetUserTypes(), "Value", "Type", user.UserType);
return View(model);
}
以下是我的观点:
<div class="form-group">
@Html.LabelFor(m => m.Branches, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.ListBox("Branches", new MultiSelectList(ViewBag.Branches, "BranchID", "Name", Model.Branches.AsEnumerable()), new { @class = "form-control branches-select" })
@Html.ValidationMessageFor(m => m.Branches)
</div>
</div>
<script src="@Url.Content("~/Scripts/chosen.jquery.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/chosen.css")" rel="stylesheet" type="text/css" />
<script> $(".branches-select").chosen(); </script>
当我使用模型中的Branches
属性时,它显示没有填充的选定值这是一个问题,当我使用另一个未在ViewModel中删除的属性然后工作正常但不与ViewModel属性我需要POST方法..
请告诉我这段代码有什么问题..
非常感谢
答案 0 :(得分:2)
尝试为ViewBag集合使用与Model属性不同的名称。
控制器
ViewBag.BranchList = db.Branches.Where(x => x.IsActive == true).AsEnumerable();
查看
@Html.ListBox("Branches", new MultiSelectList(ViewBag.BranchList,"BranchID","Name" ,Model.Branches.AsEnumerable()), new { @class = "form-control branches-select" })