1

I am trying to insert a categoryID to the table Post, but my code is creating a new category instead of using the selected value from the dropdownlist.

I am starting to study ASP.NET MVC, so I don't know how I can solve this. I can get the real value from dropdownlist but when the insert query runs it insert a new category and attribute her to 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();
}

View Code:

   <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 Model:

 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*/ //

}
JNeves
  • 41
  • 5
  • It's because this is an 'Insert', it will simply just insert. You have no checks against it. If you want to update values, you can update – JamesS Jan 09 '19 at 16:55

2 Answers2

0

Let's suppose that you have two entities Post and Category, where Category can have many Posts, i.e. entity Post has property CategoryId. Then when you build a new Post entity for insert/update you need to set CategoryId, i.e.

post.CategoryId = your_value_from_dropdown;

or you can get needed Category by CategoryID, for example,

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

and set this category for post through the navigation property like post.Category = category and then make insert or update for post.

Max
  • 1,784
  • 2
  • 19
  • 26
0

First write your Post model class as follows:

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;}
}

Looking at your Create post method it seems that problem is the following two lines:

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

Remove these two lines of code! you don't need to assign Category to Post creating a new Category with the CategoryId coming with Post. Keep your Create post method as simple as follows and it should work fine.

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);
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114