我有一个 blogPost 应该采用类别名称,为此我在 get action 中这样做了:
public ActionResult Add()
{
ViewBag.CategoryList = new SelectList(_categoryRepository.GetAllCategory(), "Id", "Name");
return View(new BlogPost());
}
在视图中我有:
@model Blog.Domain.Model.BlogPost
@{
ViewBag.Title = "AddPost";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}
<fieldset>
@using (Html.BeginForm("Add", "Blog", FormMethod.Post))
{
@Html.ValidationSummary()
<div>
@Html.LabelFor(b => b.Title)
@Html.TextBoxFor(b => b.Title)
@Html.ValidationMessageFor(b => b.Title)
</div>
<div>
@Html.LabelFor(b => b.Body)
@Html.EditorFor(b => b.Body)
@Html.ValidationMessageFor(b => b.Body)
</div>
<div>
@Html.LabelFor(b => b.Summary)
@Html.TextBoxFor(b => b.Summary)
@Html.ValidationMessageFor(b => b.Summary)
</div>
<div>
@Html.LabelFor(b => b.Category)
@Html.DropDownListFor(model => model.Category.Id, ViewBag.CategoryList as SelectList, "--- Select Category ---", new { @class = "some_class" })
</div>
<div>
<input type="submit" value="Add Post" />
</div>
}
</fieldset>
在 Post 操作中,我编写了以下代码:
[HttpPost]
public ActionResult Add(BlogPost blogPost)
{
if (ModelState.IsValid)
{
blogPost.PublishDate = DateTime.Now;
_blogPostRepository.AddPost(blogPost);
_blogPostRepository.Save();
return View();
}
return View();
}
我不确定我写的这段代码是否完全正确,但我有这个麻烦很长时间了!掌握细节插入实体框架实际上在这种情况下选择一个类别并将其成功发送到数据库,如果你之前写过这样的东西,请帮助我,谢谢