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