0

我有一个 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();
        }

我不确定我写的这段代码是否完全正确,但我有这个麻烦很长时间了!掌握细节插入实体框架实际上在这种情况下选择一个类别并将其成功发送到数据库,如果你之前写过这样的东西,请帮助我,谢谢

4

1 回答 1

0

看起来您正在设置两个下拉列表并将一个的值分配给模型的 ID 字段,我假设它是博客文章实体的 ID..?

  1. 删除 @Html.DropDownList(...) 语句
  2. 将@Html.DropDownListFor(...) 的第一个参数修改为选择模型/实体的CategoryId 属性的lambda 表达式(无论Category 的FK 字段名称是什么,大概是model => model.CategoryId)

    @Html.LabelFor(b => b.Category) @Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as SelectList, "--- Select Category ---", new { @class = "some_class" } )
于 2013-03-25T21:06:00.037 回答