如何从mvc中的多选框中预先选择?

时间:2015-09-03 07:29:16

标签: asp.net-mvc select drop-down-menu

我是mvc的新手。 我们从此链接创建了一个多选框:

How do I put data into a dropdown box and be able search for it by typing?

效果很好,但是当我实现编辑功能时,它并没有显示"研究人员"从创建选项中选择。

下面是用于创建和编辑视图的代码:

<div class="form-group">
            @Html.Label("Researchers", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                        @{
                            List<RMS.ViewModels.AssignedResearcherData> researchers = ViewBag.Researcher;
                            <select style="width: 185px; " multiple id="myDDl" class="chzn-select" name="selectedResearchers" data-placeholder="Please Select Researcher(s)">
                                @foreach (var researcher in researchers)
                                {
                                    <option value="@researcher.ResearcherID"
                                            @(Html.Raw(researcher.Assigned ? "checked=\"checked\"" : ""))>
                                        @researcher.FullName
                                    </option>
                                }
                            </select>
                        }
             </div>
        </div>

以下是编辑控制器:

// GET: Submission/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Submission submission = db.Submission.Include(i => i.Researcher).Include(i => i.CESM).Include(i => i.Publication).Include(i => i.File).Include(i => i.AdditionalFile).Where(i => i.SubmissionID == id).Single();
            PopulateAssignedResearcherData(submission);
            if (submission == null)
            {
                return HttpNotFound();
            }
            ViewBag.CESMID = new SelectList(db.CESM, "CESMID", "CESMCategory", submission.CESMID);
            ViewBag.PublicationID = new SelectList(db.Publication, "PublicationID", "Title", submission.PublicationID);
            return View(submission);
        }

        private void PopulateAssignedResearcherData(Submission submission)
        {
            var allResearchers = db.Researcher;
            var submissionResearchers = new HashSet<int>(submission.Researcher.Select(i => i.ResearcherID));
            var viewModel = new List<AssignedResearcherData>();
            foreach (var researcher in allResearchers)
            {
                viewModel.Add(new AssignedResearcherData
                {
                    ResearcherID = researcher.ResearcherID,
                    FirstName = researcher.FirstName,
                    Surname = researcher.Surname,
                    Assigned = submissionResearchers.Contains(researcher.ResearcherID)
                });
            }
            ViewBag.Researcher = viewModel;
        }

        // POST: Submission/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(int? id, string[] selectedResearchers, HttpPostedFileBase upload, HttpPostedFileBase upload2)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var submissionToUpdate = db.Submission
               .Include(i => i.Researcher)
               .Include(i => i.CESM)
               .Include(i => i.Publication)
               .Where(i => i.SubmissionID == id)
               .Single();

            if (TryUpdateModel(submissionToUpdate, "",
               new string[] { "CESMID", "PublicationID", "Type", "Title", "Status", "Comment", "SubmissionDate", "CapturedOnRIMS", "NumberOfAuthors", "NumberOfWitsAuthors", "TotalPages", "PagesInPreamble", "PagesInText", "NumberOfChapters", "Location" }))
            {

                    UpdateSubmissionResearchers(selectedResearchers, submissionToUpdate);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (RetryLimitExceededException /* dex */)
                {
                    //Log the error (uncomment dex variable name and add a line here to write a log.
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }
            PopulateAssignedResearcherData(submissionToUpdate);
            ViewBag.CESMID = new SelectList(db.CESM, "CESMID", "CESMCategory", submissionToUpdate.CESMID);
            ViewBag.PublicationID = new SelectList(db.Publication, "PublicationID", "Title", submissionToUpdate.PublicationID);
            return View(submissionToUpdate);
        }

        private void UpdateSubmissionResearchers(string[] selectedResearchers, Submission submissionToUpdate)
        {
            if (selectedResearchers == null)
            {
                submissionToUpdate.Researcher = new List<Researcher>();
                return;
            }

            var selectedResearchersHS = new HashSet<string>(selectedResearchers);
            var submissionResearchers = new HashSet<int>
                (submissionToUpdate.Researcher.Select(i => i.ResearcherID));
            foreach (var researcher in db.Researcher)
            {
                if (selectedResearchersHS.Contains(researcher.ResearcherID.ToString()))
                {
                    if (!submissionResearchers.Contains(researcher.ResearcherID))
                    {
                        submissionToUpdate.Researcher.Add(researcher);
                    }
                }
                else
                {
                    if (submissionResearchers.Contains(researcher.ResearcherID))
                    {
                        submissionToUpdate.Researcher.Remove(researcher);
                    }
                }
            }
        }

提交模型:

public class Submission
    {
        public int SubmissionID { get; set; }
        [Display(Name="Publication")]
        public int? PublicationID { get; set; }
        [Display(Name="CESM Category")]
        public int CESMID { get; set; }
        public string Type { get; set; }
        public string Title { get; set; }
        public string Status { get; set; }
        public string Comment { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Submission Date")]
        public DateTime SubmissionDate { get; set; }
        public bool CapturedOnRIMS { get; set; }
        [Display(Name = "Number Of Authors")]
        public int NumberOfAuthors { get; set; }
        [Display(Name = "Number Of Wits Authors")]
        public int NumberOfWitsAuthors { get; set; }
        [Display(Name = "Total Pages")]
        public int TotalPages { get; set; }
        [Display(Name = "Pages In Preamble")]
        public int PagesInPreamble { get; set; }
        [Display(Name = "Pages In Text")]
        public int PagesInText { get; set; }
        [Display(Name = "Number Of Chapters")]
        public int NumberOfChapters { get; set; }
        public string Location { get; set; }
        public virtual ICollection<Researcher> Researcher { get; set; }
        public virtual Publication Publication { get; set; }
        public virtual CESM CESM { get; set; }
        [Display(Name="Document")]
        public virtual ICollection<File> File { get; set; }
        [Display(Name="Additional Document")]
        public virtual ICollection<AdditionalFile> AdditionalFile { get; set; }
    }

研究员模型:

public class Researcher
    {
        public int ResearcherID { get; set; }
        [Display(Name="School")]
        public int SchoolID { get; set; }
        [Required]
        [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Required]
        [StringLength(50)]
        public string Surname { get; set; }       
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Registration Date")]
        public DateTime RegistrationDate { get; set; }
        [Display(Name = "Qualification Type")]
        public string QualificationType { get; set; }
        [Display(Name = "Job Name")]
        public string JobName { get; set; }
        public string Availability { get; set; }
        [Display(Name="Researcher Full Name")]
        public string FullName
        {
            get
            {
                return Surname + ", " + FirstName;
            }
        }
        public virtual ICollection<Submission> Submission { get; set; }
        public virtual School School { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

我在编辑视图中犯了一个愚蠢的错误。 我更换了#34;已检查&#34;选择&#34; <#34;

下面的

是新的编辑视图:

<div class="form-group">
            @Html.Label("Researchers", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                        @{
                            List<RMS.ViewModels.AssignedResearcherData> researchers = ViewBag.Researcher;
                            <select multiple id="myDDl" class="chzn-select" name="selectedResearchers" >
                                @*<option selected=""></option>*@
                                @foreach (var researcher in researchers)
                                {
                                    <option value="@researcher.ResearcherID"
                                            @(Html.Raw(researcher.Assigned ? "selected=\"selected\"" : ""))>
                                        @researcher.FullName
                                    </option>
                                }
                            </select>
                        }
                </div>
            </div>