DropDownList 值作为外键插入数据库

DropDownList value insert in database as foreign key

我正在尝试将 categoryID 插入到 table Post,但我的代码正在创建一个新类别,而不是使用从下拉列表中选择的值。

我开始研究ASP.NET MVC,所以我不知道如何解决这个问题。我可以从下拉列表中获取实际值,但是当插入查询运行时,它会插入一个新类别并将她归因于 post insert.

public ActionResult Create([Bind(Include = "PostID,Text,CategoryID")] Posts posts)
{
    if (ModelState.IsValid)
    {
        int CategoryID = Convert.ToInt32(Request["CategoryID"]);
        posts.Category = new Categories { CategoryID = CategoryID };
        db.Posts.Add(posts);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(posts);
}

public ActionResult Create()
{
    ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "Name");
    return View();
}

查看代码:

   <h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Posts</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Text, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Text, "", new { @class = "text-danger" })

                Categoria:<br />
                @Html.DropDownList("CategoryID", "Selecione uma categoria")
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Post 型号:

 public class Post
{
    [Key]
    public int PostID { get; set; } /*PRIMARY KEY*/
    public string Text { get; set; }

    public virtual Categories Category { get; set;} /*ONE POST HAS ONLY ONE CATEGORY*/ //

}

假设您有两个实体 PostCategory,其中 Category 可以有多个 Posts,即实体 Post 有 属性 CategoryId。然后,当您为 insert/update 构建新的 Post 实体时,您需要设置 CategoryId,即

post.CategoryId = your_value_from_dropdown;

或者您可以通过CategoryID获取需要的分类,例如

var category = db.Category.Where(x => x.CategoryId == your_value_from_dropdown).FirstOrDefault(); 

并通过导航 属性 为 post 设置此类别,例如 post.Category = category,然后为 post.

进行插入或更新

首先写下你的Post模型class如下:

public class Post
{
    [Key]
    public int PostId {get; set;}

    public string Text {get; set;}

    [ForeignKey("Category")]
    public int CategoryID {get; set;}

    public Category Category {get; set;}
}

查看您的 Create post 方法,问题似乎出在以下两行:

int CategoryID = Convert.ToInt32(Request["CategoryID"]);
posts.Category = new Categories { CategoryID = CategoryID };

去掉这两行代码!您不需要将 Category 分配给 Post 创建一个新的 CategoryCategoryIdPost 一起出现。保持您的 Create post 方法简单如下,它应该可以正常工作。

public ActionResult Create([Bind(Include = "PostID,Text,CategoryID")] Posts posts)
{
    if (ModelState.IsValid)
    {
        db.Posts.Add(posts);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(posts);
}