且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在asp.net mvc 中获取多选的下拉列表值

更新时间:2023-10-10 16:06:22

我的建议是你的模型需要与你的多选列表中的项目有一对多的关系.

What I suggest is that your model needs to have a one to many relationship with the items in your multi select list.

一个例子是一个有多个标签的博客:

An example is a Blog with multiple tags:

您的博客模型可能如下所示:

Your blog model may look like:

public class Blog
{
    public Blog()
    {
        Tags = new List<Tag>();
    }

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

你的标签模型是这样的:

And your tag model like so:

    public int TagID{ get; set; }
    public string TagName{ get; set; }
    public virtual ICollection<Blog> Blogs{ get; set; }

现在我建议你使用视图模型:

Now I recommend you use a view model:

public class BlogViewModel
{
    public Blog blog{ get; set; }
    public List<int> SelectedTags { get; set; }

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

    public BlogViewModel()
    {

    }

    public BlogViewModel(Blog _blog, List<Tag> _Tags)
    {
        blog = _blog;
        Tags = _Tags;
        SelectedTags = new List<int>();
    }
}

最后在您的视图中(从 ViewModel 继承);

And finally in your View (which inherits from the ViewModel);

@Html.ListBoxFor(m => m.SelectedTags,
new MultiSelectList(Model.Tags, "TagID", "Tag")
, null)

JQuery Chosen 插件非常适合这个http://harvesthq.github.io/chosen/.您可以通过以下方式使用它:

The JQuery Chosen plugin is excellent for this http://harvesthq.github.io/chosen/. You can use it by:

@Html.ListBoxFor(m => m.SelectedTags,
new MultiSelectList(Model.Tags, "TagID", "Tag")
, new { @class = "chzn-select", data_placeholder = "Tags..." })

用您自己的模型和控制器替换它,这应该可以解决您的问题.此外,这将适用于您的表单,用于创建新博客文章和编辑现有文章(添加和删除标签)

Replace this with your own model and controllers and this should solve your problem. Also, this will work in your form for creating a new blog post, and for editing an existing post (adding and removing tags)

在您的博客创建控制器操作中,您可以将其填充为:

In your Blog Create controller action, you would populate this as:

    public ActionResult Create()
    {

        var blog = new Blog();
        var AllTags = from t in db.Tags
                           select t;
        BlogViewModel viewModel = new BlogViewModel(blog,
            Tags.ToList());

        return View(viewModel);

    }

    public ActionResult Create(BlogViewModel blogViewModel)
    {
        Blog blog = blogViewModel.blog;

        if (blogViewModel.SelectedTags != null)
        {
            foreach (var TagID in blogViewModel.SelectedTags)
            {
                Tag tag = db.Tags.Where(t => t.TagID == TagID).First();
                blog.Tags.Add(tag);
            }
        }
        db.Blog.Add(blog);
        db.SaveChanges();
    }