jacksparrow jacksparrow - 2 months ago 51
Ajax Question

MVC 5 Ajax BeginForm POST 404 Not Found

I have a problem with my MVC application.

My controller:

public class CustomerController : Controller
{

public ActionResult Index()
{
return View();
}


public ActionResult Create()
{
return View();
}

[HttpPost]
public ActionResult Create(Customers customers)
{
//do something
return View();
}
}


My view:

@model Insurance_System.Models.Customers
<script src="~/Scripts/jquery-3.1.0.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">

<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Dodawanie nowego klienta</h4>
</div>
<div class="modal-body">
@using (Ajax.BeginForm("Create", "CustomerController", null, new AjaxOptions { HttpMethod = "POST" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<div class="col-md-4">
@Html.TextBoxFor(model => model.FirstName, new { @required = "require", @class = "form-control", placeholder = @Resources.InsuranceCustomer.FirstName })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
<div class="col-md-4">
@Html.TextBoxFor(model => model.LastName, new { @required = "require", @class = "form-control", placeholder = @Resources.InsuranceCustomer.LastName })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>

// and other field form
</div>

<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="@Resources.Common.Save" class="btn btn-success" />
</div>
}
@*<div>
@Html.ActionLink("Back to List", "Index")
</div>*@
</div>
</div>
</div>
</div>


I use this form in my other View:

@Html.Partial("~/Views/Customer/CreateModal.cshtml")


CreateModel (form) render on bootstram modalpopup.
When I fill form and submit changes, browser show error:


POST http://localhost:8001/CustomerController/Create 404 (Not Found)
- [jquery-3.1.0.js:9392]


I start play with MVC, so far I coped eny problem:)

Answer

You do not need the Controller suffix when specifying the controller name.

Use Customer instead of CustomerController.

@using (Ajax.BeginForm("Create", "Customer", null,new AjaxOptions { HttpMethod = "POST" }))
{

}
Comments