When writing MVC code you cannot forget jQuery. jQuery provides a substantial contribution to make your application faster.
The following is what is to be discussed:
- using $.get()
- using $.post()
- using $.ajax()
- using URL (JavaScript style)
When you are writing jQuery code, one thing to keep in your mind is that you need to minimize page loading/refreshing.
http://blogs.mooncopula.com/Home/BlogPage?blogid=4
$.get() method
- Calling Controller Action without parameter.
Controller:
- public string SaveEmployeeRecord()
- {
- string res = "this is return value";
-
- return res;
- }
View:
- $.get("/Home/SaveEmployeeRecord",null, function (data) {
- alert(data);
- });
- Calling Controller Action with parameter.
Controller:
- public string SaveEmployeeRecord(string name)
- {
- string res = name;
-
- return res;
- }
View:
- $.get("/Home/SaveEmployeeRecord", {name:'Deepak'}, function (data) {
- alert(data);
- });
- Calling Controller Action with parameter returning JSON data.
Controller:
- public JsonResult SaveEmployeeRecord(string id,string name)
- {
- string this_id = id;
- string this_name = name;
-
- return Json(new {id=this_id,name = this_name },JsonRequestBehavior.AllowGet);
- }
View:
- $.get("/Home/SaveEmployeeRecord", {id:'67',name:'Deepak'}, function (data) {
- alert(data.id);
- alert(data.name);
- });
$.post() method
The syntax and use of the post method is just like the get method. Here instead of using the get keyword, use the post keyword and all the other things are the same.
- Calling Controller Action without parameter.
Controller:
- public string SaveEmployeeRecord()
- {
- string res = "this is return value";
-
- return res;
- }
View:
- $.post("/Home/SaveEmployeeRecord",null, function (data) {
- alert(data);
- });
- Calling Controller Action with parameter.
Controller:
- public string SaveEmployeeRecord(string name)
- {
- string res = name;
-
- return res;
- }
View:
- $.post("/Home/SaveEmployeeRecord", {name:'Deepak'}, function (data) {
- alert(data);
- });
- Calling Controller Action with parameter returning JSON data.
Controller:
- public JsonResult SaveEmployeeRecord(string id,string name)
- {
- string this_id = id;
- string this_name = name;
-
- return Json(new {id=this_id,name = this_name },JsonRequestBehavior.AllowGet);
- }
View:
- $.post("/Home/SaveEmployeeRecord", {id:'67',name:'Deepak'}, function (data) {
- alert(data.id);
- alert(data.name);
- });
$.ajax() method
- Calling Controller Action with parameter returning JSON data.
Controller:
- public JsonResult SaveEmployeeRecord(string id,string name)
- {
- string this_id = id;
- string this_name = name;
-
- return Json(new {id=this_id,name = this_name },JsonRequestBehavior.AllowGet);
- }
View:
- $.ajax({
- type: 'POST',
- dataType: 'json',
- url: '/Home/SaveEmployeeRecord',
- data: { id: '67', name: 'Deepak' },
- success: function (Data) {
- alert(data.id);
- alert(data.name);
- },
- error: function (XMLHttpRequest, textStatus, errorThrown) {
-
- }
- });