JQuery Ajax in ASP.Net MVC 4
In this
blog, I am explaining the jquery ajax in asp.net mvc4 and how to call the
action method of the controller from the view using the ajax.
Step 1
First
create a basic asp.net mvc 4 application and add a controller to the project
named “HomeController” like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JQueyAjaxMvcApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public string SendSms(string number)
{
return "Confirmation
message has been send to the mobile number : " + number;
}
}
}
Step 2
Now add a
view to the project – so right click near the action method Index and select
the Add view option and write the below in it:
@{
ViewBag.Title =
"Index";
}
<h2>Index</h2>
<html>
<head>
<script src="@Url.Content("~/Scripts/jquery-1.7.1.js")"></script>
<script type="text/javascript">
$(function () {
$('#btnSend').click(function () {
$.ajax({
type: 'GET',
url: "/Home/SendSms",
data: { number: $('#txtMobileNumber').val() },
success: function (data) {
$("#rData").html(data);
}
});
});
});
</script>
</head>
<body>
<div>
<div>
Enter
Your Mobile Number :
@Html.TextBox("txtMobileNumber")
<input type="button" id="btnSend" value="Send" />
</div>
<br />
<div id="rData">
</div>
</div>
</body>
</html>
Output
Now run the
application:
Enter a
mobile number in the textbox and click send button:
You will a
have a confirmation message like this:
Thank you for reading this article, please
put your valuable comment or any suggestion/question in the comment box.
No comments:
Post a Comment