Jquery选择多选MVC 5在编辑表单上没有填充选择值

本文关键字:选择 填充 表单 MVC Jquery 编辑 | 更新日期: 2023-09-27 18:08:23

这是我的视图模型:

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方法..

请告诉我这个代码有什么问题。

Thanks to lot

Jquery选择多选MVC 5在编辑表单上没有填充选择值

尝试为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" })