I am pulling my hair due to many to many relationship between my entities Contacts and Tags. Now when I am editing a Contact I want to render all the tags in database and select those who are already linked with this contact (when contact inserted).

public class Contact
{
    public Contact()
    {
        isNewsletterSubscriber = true;
        CreatedOn = DateTime.Now;
    }

    public int ContactID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string Email { get; set; }

    public string Organization { get; set; }

    public string CellPhone { get; set; }

    public string Designation { get; set; }

    public string Address { get; set; }

    public string PhoneNumber { get; set; }

    public bool isNewsletterSubscriber { get; set; }

    public string Twitter { get; set; }
    public string Facebook { get; set; }

    public DateTime CreatedOn { get; set; }

    public virtual ICollection<Tag> Tags { get; set; }


}

public class Tag {

    public Tag()
    {
        CreatedOn = DateTime.Now;
    }
    public int TagID { get; set; }
    public string Name { get; set; }
    public DateTime CreatedOn { get; set; }

    public virtual ICollection<Contact> Contacts { get; set; }

}

My edit view inside controller is bind to strongly typed model Contact showing above. Code for action is following.

 public ActionResult Edit(int id) {
        var contact = _repo.Find(x => x.ContactID == id).FirstOrDefault();     


        //loading tags
        var allTags = _repoTags.Get().ToList();
        var selected = contact.Tags.Select(s => s.TagID);
        string[] selecteds= new string[]{"1","2"};
        this.ViewBag.Tags = new MultiSelectList(allTags, "TagID", "Name", selecteds);

        //var selectListTags = allTags.Select(x => new SelectListItem
        //{
        //    Text = x.Name,
        //    Value = x.TagID.ToString()
        //}).ToList();

        //ViewBag.cTags = selectListTags;

        //ViewBag.cTags = new SelectList(allTags, "TagID", "Name", 
        //    contact.Tags.Select(x=> new { TagID = x.TagID.ToString()}));



        return View(contact);
    }

inside my razor view i am using following code @Html.ListBoxFor(m => m.Tags, this.ViewBag.JustMakeUpANameHere as MultiSelectList)

its showing a list box when edit view loads with contact details but multiselect box is not showing the selected tags which this contact already has.

Help.

Related posts

Recent Viewed