I am having trouble submitting forms without a post back using AJAX. My code is not working as expected.
What could be the issue in my script?
I am new to AJAX and would appreciate some help with AJAX scripts.
Below you can find my code:
Please note: I have two submit buttons within a single view. I want to make an AJAX call for both submit actions.
My View
@model AjaxEF.Models.Customer
@using (Html.BeginForm("Index", "Main", FormMethod.Post,new { id="idForm"}))
{
@Html.EditorForModel()
<br />
<input type="submit" name="save" value="Save" />
<input type="submit" name="cancel" value="Cancel" />
}
<script>
$("#idForm").submit(function (e) {
e.preventDefault(); // prevent the actual submit of the form.
var url = "~/Main/Result"; // specify the script where form input will be handled.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serialize the form's elements.
success: function (data) {
alert(data); // display response from the server script.
}
});
});
</script>
My Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer obj, string save, string cancel)
{
if (!string.IsNullOrEmpty(save))
{
ViewBag.Message = "Customer saved successfully!";
}
if (!string.IsNullOrEmpty(cancel))
{
ViewBag.Message = "The operation was cancelled!";
}
return View("Result", obj);
}
public ActionResult Result()
{
return View();
}