Mvc 4 MultiSelect list & EF for many

I have these entities (there are many, many links between them):

public class Post
{     
    public Guid PostId { get; set; }     
    public string Name { get; set; }       
    public virtual ICollection<Tag> Tags { get; set; }
}

  public class Tag
{
    public int TagId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

I would like the user, when he created Post, to select data from MultiSelectList and MultiSelectList to transfer this data to Post.Tags. How can i do this?

+5
source share
1 answer

I have something similar, the product belongs to many categories and categories, it has many products.

In my administrative view to create new products, I can allow the user to select mutliple "tags" for the categories in which this product should be listed.

- - auto ajax jQuery, TagIt.

public class HomeController : Controller
{
    public ActionResult Create()
    {
        var tags = new List<Tag>()
            {
                new Tag() { TagId = 1, Name = "Planes", Posts = new Collection<Post>() },
                new Tag() { TagId = 2, Name = "Cars", Posts = new Collection<Post>() },
                new Tag() { TagId = 2, Name = "Boats", Posts = new Collection<Post>() }
            };

        ViewBag.MultiSelectTags = new MultiSelectList(tags, "TagId", "Name");

        return View();
    }

    [HttpPost]
    public ActionResult Create(Post post, int[] tags) // Tags is not case-sensative from model binder when html element name="tags" <-- array passed back to controller
    {

        // Find Tag from Database
        // Attach tag entity to Post

        // foreach(var tagId in tags)
        //    var tag = context.Tags.find(tagId)
        //    post.Tags.Add(tag);

        // context.SaveChanges();

        return RedirectToAction("Create");
    }

}

View/Create.cshtml

@model MvcApplication1.Models.Post

<h2>Create</h2>


@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
    <label>Name</label>
    @Html.TextBoxFor(model => model.Name)

    <label>Tags For Post</label>
    @Html.ListBox("Tags", (MultiSelectList)ViewBag.MultiSelectTags)

    <input type="submit" value="Submit Post"/>
}

all :

Vm3jU7v.png

, , , , html- ""

pWBsCfW.png

+13

All Articles