Ajax Call In MVC
In my previous blog I had explained Ajax Call in Asp.Net. Now I will explain Ajax Call in MVC.
Here, I will explain how to set value of textboxes in model's property and how to set property's value in textboxes.
Under Models
Create a model as Student.cs
namespace MvcApplicationWithAjax.Models
{
public class Student
{
public int Id{get;set;}
public string Name{get;set;}
public string Address{get;set;}
}
}
Here, I have declared a model as Student.cs with properties Id,Name and Address.
Views
@model MvcApplicationWithAjax.Models.Student
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
function Post()
{
var name = $("#txtName").val();
var id = $("#txtId").val();
var address = $("#txtAddress").val();
var s = {
Name: name,
Id: id,
Address: address
};
$.ajax({
type: "POST",
url: "Home/Save",
//data: '{name:"' + txtName.value + '",Id:"' + txtId.value + '",Add:"' + txtAddress.value + '"}',
data:JSON.stringify(s),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
failure: function (response) {
alert("some error occourred...");
}
});
}
function Get() {
$.ajax({
type: "POST",
url: "Home/Display",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var obj = response;
txtIdView.value = obj.Id;
txtNameView.value = obj.Name;
txtAddressView.value = obj.Address;
},
failure: function (response) {
alert("some error occourred...");
}
});
}
</script>
<h2>Index</h2>
<form name="form1" method="post">
<table id="adduser">
<tr><td>Id</td> <td><input type="text" id="txtId"></td></tr>
<tr>
<td>
Name
</td>
<td><input type="text" id="txtName"></td>
</tr>
<tr>
<td>
Address
</td>
<td>
<input type="text" id="txtAddress">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="submit" name="submit" value="Save" onclick="Post();">
</td>
</tr>
</table>
</form>
<form name="form2" method="get">
<table id="viewDetails">
<tr>
<td></td>
<td>
<input type="button" id="submitView" name="submit" value="Display" onclick="Get()">
</td>
</tr>
<tr><td>Id</td> <td><input type="text" id="txtIdView"></td></tr>
<tr>
<td>
Name
</td>
<td><input type="text" id="txtNameView"></td>
</tr>
<tr>
<td>
Address
</td>
<td>
<input type="text" id="txtAddressView">
</td>
</tr>
</table>
</form>
Here,I have created two forms "form1" and "form2". "form1" contains three textboxes for Id,Name and Address. As user enters value and clicks on "Save" it will make a call to function defined in onlick event(calls javascript's Post() function).
From Post() function there is an ajax call to action "Save" of HomeController.
Explanation
Creating JSON object
Json object consist of name/value pairs.
Json objects are written inside curly braces.
Json object can contain multiple values.
Example
var s = {
Name: name,
Id: id,
Address: address
};
Ajax Call and Parsing JSON object(Inside function Post())
$.ajax({
type: "POST",
url: "Home/Save",
//data: '{name:"' + txtName.value + '",Id:"' + txtId.value + '",Add:"' + txtAddress.value '"}',
data:JSON.stringify(s),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
failure: function (response) {
alert("some error occourred...");
}
});
}
type: "POST"
Attribute type of ajax call defines the type of ajax call. It can be either Post or Get.
url: "Home/Save" (ControllerName/ActionName)
Attribute "url" of ajax call defines the name of particular Action of particular Controller to which we have to send data as parameter. Here, we have to send data to Action "Save" of Controller.
data:JSON.stringify(s)
Attribute "data" defines the data which we have to send to defined url. Here, we have to send the data as Json object so, we have used stringify() function to parse Json in string format.
JSON.stringify(s)
Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
contentType: "application/json; charset=utf-8"
Attribute "contentType"` is the header for your request & utf-8 defines the encoding.
dataType: "json"
Attribute "datatype" defines the type of data here we are sending data as "json" object. But when we have to send multiple values we have to wrap values in object and send it as json object.
success: function (response) {
alert(response);
}
If ajax call is successful then we will be inside on success function and parameter "response" contains the result returned from the Action "Save". Here, response contains "Successful".
failure: function (response) {
alert("some error occurred...");
}
If ajax call fails then message inside alert will be prompted.
"form2" contains three textboxes for Id,Name and Address.As user clicks on "Display" it will make a call to function defined in onlick event(calls javascript's Get() function).
From Get() function there is an ajax call to action "Display" of HomeController.
Ajax Call Inside function Get()
$.ajax({
type: "POST",
url: "Home/Display",
// data: '{value:"' + value '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var obj = response;
txtIdView.value = obj.Id;
txtNameView.value = obj.Name;
txtAddressView.value = obj.Address;
},
failure: function (response) {
alert("some error occurred...");
}
});
For "data" field you may send any value or Id, on the basis of which you want to fetch record. Here, I am fetching hard coded values so I have commented data field.
Here, only change is in on Success function, response contains the object and value of textboxes are set to values of object's properties.
Controllers
namespace MvcApplicationWithAjax.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Save(Student student)
{
string name = student.Name;
int id = student.Id;
string address = student.Address;
return Json("Successful");
}
[HttpPost]
public JsonResult Display()
{
Student student = new Student();
student.Name = "priyank";
student.Id = 3;
student.Address = "Clementown";
return Json(student, JsonRequestBehavior.AllowGet);
}
}
}
Here,I have defined a controller as HomeController and I have created two actions as "Save" and "Display".
When user clicks on "Save" values entered in textboxes are set to model's properties through ajax call and "Successful" is returned but we can also use these values for database operations.
When user clicks on "Display" ajax call to action Display is made and values are set to object's property and object is returned and value of object's properties are set to textboxes.
0 Comment(s)