In this article we will learn with an example, Submit Form using jQuery in ASP.Net MVC
This article will explain how to Submit Form using jQuery in ASP.Net MVC.
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling AJAX POST operation
This Action method handles the Ajax Form submission and it accepts the value of the Form elements as parameter.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string firstName, string middleName)
{
if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(middleName))
{
string name = string.Format(“Name: {0} {1}”, firstName, middleName);
return Json(true);
}
return Json(false);
}
}
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. My action name is Index.
ControllerName – Name of the Controller. My controller name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width”/>
<title>Index</title>
</head>
<body>
@using (Html.BeginForm(“Index”, “Home”, FormMethod.Post, new { @id = “myFormSubmit” }))
{
<table>
<tr>
<td>First Name: </td>
<td><input type=”text” id=”txtFirstName”/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type=”text” id=”txtMiddleName”/></td>
</tr>
<tr>
<td></td>
<td><input type=”button” value=”Submit” onclick=”AjaxFormSubmit()”/></td>
</tr>
</table>
}
<script type=”text/javascript” src=”https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>
<script type=”text/javascript”>
function AjaxFormSubmit() {
//Set the URL.
var url = $(“#myFormSubmit”).attr(“action”);
//Add the Field values to FormData object.
var formData = new FormData();
formData.append(“firstName”, $(“#txtFirstName”).val());
formData.append(“middleName”, $(“#txtMiddleName”).val());
$.ajax({
type: ‘POST’,
url: url,
data: formData,
processData: false,
contentType: false
}).done(function (response) {
if (response) {
alert(“Form successfully submitted!”);
}
else {
alert(“Invalid Form data!”);
}
});
}
</script>
</body>
</html>