In this post, I will create a simple jQuery Post method example using ASP.NET MVC.
First, lets take a look at the controller code. The PostController has 2 action methods, one which just displays the index view and the other one which will be fired when the client browser submits a post request. The post method PostExample, for the sake of simplicity, doesn't do any business logic and just sends back the value it received from client to demonstrate a full cycle. In this case we are using the type as JSON but we could have very well used XML or HTML.
First, lets take a look at the controller code. The PostController has 2 action methods, one which just displays the index view and the other one which will be fired when the client browser submits a post request. The post method PostExample, for the sake of simplicity, doesn't do any business logic and just sends back the value it received from client to demonstrate a full cycle. In this case we are using the type as JSON but we could have very well used XML or HTML.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AjaxSample.Controllers { public class PostController : Controller { public ActionResult Index() { return View(); } public JsonResult PostExample(int count) { // do some processing here var res = new Result {Text = "Received and processed " + count + " successfully."}; return Json(res); } } public class Result { public string Text { get; set; } } }Now, let's take a look at the view. The view just contains a text box, a button and an empty div tag at the beginning. The script shows that when the button is clicked, a post request is fired with input arguments as the value user entered in the text box. If the operation is successful, the server returns a text message which is applied to the div tag.
Enter count: <input type="text" id="inp" /> <input type="button" value="Fire a post request" id="btnPost" /> <div id="ajaxDiv"> </div> <script type="text/javascript"> $(document).ready(function () { $('#btnPost').click(function () { var enteredData = $('#inp').val(); $.post("/Post/PostExample", { count: enteredData }, function (data) { $('#ajaxDiv').text(data.Text); }, "json"); }); }); </script>Here is how the output looks: