我的控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(BlogCompModel blogmodel)
{
if (ModelState.IsValid)
{
...
}
}
我的观点:
@model BlogProject.Models.BlogCompModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
...
<div class="form-group">
@Html.LabelFor(model => model.BlogCompModel.posts, "Property", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBoxFor(model => model.posts, new MultiSelectList(Model.posts, "post_ID", "postTitle"))
@Html.ValidationMessageFor(model => model.posts.posts)
</div>
</div>
}
帖子上的错误消息:
"The parameter conversion from type 'System.String' to type 'BlogProject.Models.Posts' failed because no type converter can convert between these types."} System.Exception {System.InvalidOperationException}
正如您所看到的,我不确定如何将HTML Multiselect列表从Post_ID集合转换为ICollection的帖子。
谢谢!
答案 0 :(得分:1)
您可以在BlogCompModel
模型中添加其他属性,它会将所有选定的帖子包装在其中。
public class BlogCompModel
{
//
public string[] selectedPosts { get; set; }
}
然后在你看来:
@Html.ListBoxFor(model => model.selectedPosts ,
new MultiSelectList(Model.posts, "post_ID", "postTitle"))
@Html.ValidationMessageFor(model => model.selectedPosts )
答案 1 :(得分:0)
在我的博客MVC应用程序中,我有一个用于标签的多选项,以及我如何将这些添加到Post in Create操作中。
<强> Index.cshtml 强>
@model MyBlog.Core.Post
@Html.ListBox("PostTags", (MultiSelectList)ViewBag.MultiSelectList, new { @class = "form-control" })
控制器
public ActionResult CreatePost([Bind(Include = "Id,Title,ShortDescription,Description,Published,PostedOn,ModifiedOn,CategoryId")] Post post, int[] postTags)
{
if (postTags != null)
{
foreach (var t in postTags)
{
var tag = _dbTag.GetById(t);
post.Tags.Add(tag);
}
}
// save to database and other stuff
return View(post);
}