我在获取多选下拉列表值时遇到问题。任何人都可以建议我如何获取选择多个下拉列表值以及如何在 Controller 中获取它们。
我的代码是这样的:-
型号
public string BusinessUnitSiteSafetyRepresentative { get; set; }
Controller
[HttpPost]
public ActionResult AddClientBusinessUnitSite(LocalAddClientBusinessUnitSite local)
{
var query = from o in entitydb.systemusersorganizations.toList()
from c in entitydb.contacts.toList()
where o.orgId == clientId
select new SelectListItem
{
Text = c. Name;
Value = c.OrgId.toString()
}
ViewBag.list1 = query.ToList();
}
好吧,如果选择单个值,我可以得到并可以保存到 DB。但是如何选择多个值以及将它们放入 Controller 中以保存它们。
注意: - 我正在从数据库中检索下拉列表值,如上所示。
查看
@Html.ListBoxFor(x => Model.BusinessUnitSiteSafetyRepresentative,new
MultiSelectList((IEnumerable<SelectListItem>)@Viewbag.list1)
我已经经历了一些例子,但没有一个对我有帮助。请帮助我。
最佳答案
我的建议是您的模型需要与多选列表中的项目有一对多的关系。
一个例子是一个带有多个标签的博客:
您的博客模型可能如下所示:
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; }
}
你的标签模型是这样的:
public int TagID{ get; set; }
public string TagName{ get; set; }
public virtual ICollection<Blog> Blogs{ get; set; }
现在我建议您使用 View 模型:
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>();
}
}
最后在您的 View 中(从 ViewModel 继承);
@Html.ListBoxFor(m => m.SelectedTags,
new MultiSelectList(Model.Tags, "TagID", "Tag")
, null)
JQuery 选择插件非常适合这个 http://harvesthq.github.io/chosen/ .您可以通过以下方式使用它:
@Html.ListBoxFor(m => m.SelectedTags,
new MultiSelectList(Model.Tags, "TagID", "Tag")
, new { @class = "chzn-select", data_placeholder = "Tags..." })
用您自己的模型和 Controller 替换它,这应该可以解决您的问题。此外,这将适用于您的表单,用于创建新博客文章和编辑现有文章(添加和删除标签)
编辑:
在您的博客创建 Controller 操作中,您可以将其填充为:
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();
}
关于asp.net-mvc - 如何在asp.net mvc中获取多选下拉列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17021978/