Reputation: 326
I have a problem here with regards to elements on my pages returning null
even though I have typed something in the textbox. What causes this? I want to make a simple CRUD app with a dashboard for final year.
Here is my view:
@model WebApplication1.Models.Category
@{
ViewBag.Title = "Create Category";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class
="control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Name, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new {
@class = "text-danger" })
</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")
}
Here is my controller action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name")] Category category)
{
if (ModelState.IsValid)
{
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
Upvotes: 0
Views: 52
Reputation: 24957
Make sure that you have proper viewmodel properties setup first:
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
Then point to action name and controller name which handles POST action in BeginForm
helper:
@* assumed the controller name is 'CategoryController' *@
@using (Html.BeginForm("Create", "Category", FormMethod.Post))
{
// form contents
}
And finally change parameter name to avoid naming conflict in default model binder, also remove BindAttribute
because the POST action has strongly-typed viewmodel class as parameter:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Category model)
{
if (ModelState.IsValid)
{
db.Categories.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
Related issue:
POST action passing null ViewModel
Upvotes: 1
Reputation: 35514
I think you need to post to the correct ActionName. You use @using (Html.BeginForm())
, which will post to the Index of a Controller. But you have Create
. So point the form to that.
@using (Html.BeginForm("Create", "Home", FormMethod.Post))
Upvotes: 2