使用Entity框架创建Master详细信息

时间:2013-03-25 16:29:41

标签: asp.net-mvc-3 entity-framework

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

我不确定我是否完全正确地编写了这段代码,但我已经麻烦了一次!用实体框架插入主要细节实际上在这种情况下选择一个类别并成功发送到数据库,如果你之前写过类似的东西,请帮助我,谢谢

1 个答案:

答案 0 :(得分:0)

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

  1. 删除@ Html.DropDownList(...)语句
  2. 将@ Html.DropDownListFor(...)的第一个参数修改为lambda表达式,选择模型/实体的CategoryId属性(无论FK字段名称是否为Category,可能是model =&gt; model。类别ID)

        @ Html.LabelFor(b =&gt; b.Category)     @ Html.DropDownListFor(model =&gt; model.CategoryId,ViewBag.CategoryList as SelectList,“--- Select Category ---”,new {@class =“some_class”})