Kivan Ilangakoon
Kivan Ilangakoon

Reputation: 457

how to pre-select from a multiple select box in mvc?

I am new to mvc. we got this code to create a multiple select box from the link:

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

It works well, however when I implement the edit functionality, it doesn't display the "Researchers" selected from the create option.

below is the code used for the create and edit View:

<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>

Below is the edit controller:

// 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);
                    }
                }
            }
        }

Submission Model:

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; }
    }

Researcher Model:

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; }
    }

Upvotes: 0

Views: 117

Answers (1)

Kivan Ilangakoon
Kivan Ilangakoon

Reputation: 457

It was a silly mistake I had made in the edit view. I replaced "checked" with "selected"

below is the new edit view:

<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>

Upvotes: 1

Related Questions