Saturday 30 July 2016

How to use $.post , $.getJSON , $.ajax in Asp.Net MVC

How to use $.post , $.getJSON , $.ajax  in Asp.Net MVC

---Sql query

create table Student
(
RollNo int primary key,
Name varchar(50) not null,
Gender varchar(50) not null,
Course varchar(50)
)

create table Course
(
CourseId int primary key,
CourseName varchar(50) not null
)
--**************************----
Note :  Here  we  will discuss $.post method and $.getJson method in Mvc
We will create Controller which name Home in MVC Application ……………………..
Code for HomeController.cs……………………………………
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AjaxMethodInMvc.Models;

namespace AjaxMethodInMvc.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
testEntities database = new testEntities();

[HttpGet]
public ActionResult Index()
{

//ViewBag.Course = (from m in database.Courses select new SelectListItem { Text = m.CourseName, Value = m.CourseId.ToString() }).ToList();

ViewBag.Course = new SelectList(database.Courses, "CourseId", "CourseName", "Select");
return View();

}

[HttpPost]
public JsonResult Save(string _RollNo,string _Name,string _Gender,string _Course)
{
try
{
if (string.IsNullOrEmpty(_RollNo))
{
throw new Exception("Please enter RollNo");
}
Student ss = new Student
{
RollNo=Convert.ToInt32(_RollNo),
Name=_Name,
Gender=_Gender,
Course=_Course
};
database.Students.Add(ss);
database.SaveChanges();
return this.Json(new { result = true, msg = "data save" });
}

catch (Exception ex)
{
return this.Json(new { result = false, msg = ex.Message });
}
}


[HttpGet]
public JsonResult GetList(string name)
{
System.Threading.Thread.Sleep(2000);
return this.Json(this.database.Students.Where(obj => obj.Name.StartsWith(name)).ToList(), JsonRequestBehavior.AllowGet);

}

}
}

Code for  Index.cshtml……………………………………
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery-1.7.1.intellisense.js"></script>
<script type="text/javascript">

$(function ()
{

/************************** start code**************/
$(':button').click(function ()
{

//alert($("input[name=Gender]:checked").val());
// var v = $("#Course option:selected").text();

var v = { _RollNo: $('#RollNo').val(), _Name: $('#Name').val(), _Gender: $("input[name=Gender]:checked").val(), _Course: $("#Course option:selected").text() };
$.post("home/save", v, function (data) {

$('#msg').html(data.msg);
$('#msg').slideDown(1000).delay(2000).fadeOut(1000, function () {

if (data.result) {
$('#RollNo').val("").focus();
$('#Name').val("");
}
});
});

});

/************** end code *******************/


/************************** start code**************/

$('#name').keyup(function ()
{

var v = $(this).val();
var data = null;
if (v.length >= 2)
{

$('#loader').show();
$.getJSON("home/GetList/?name=" + v, null, function (data) {
$('#loader').hide();
$('#table1').html("");
$.each(data, function (i, d)
{
data += "<tr><td>" + d.RollNo + "</td><td>" + d.Name + "</td><td>" + d.Gender + "</td><td>" + d.Course + "</td></tr>";

});

$('#table1').append(data);

});


}
});

/**************  end code *******************/
});
</script>

</head>
<body>

<table style="margin-top:54px">
<tr><td>RollNo</td><td>@Html.TextBox("RollNo")</td></tr>
<tr><td>Name</td><td>@Html.TextBox("Name")</td></tr>
<tr><td>Gender</td><td>Male:@Html.RadioButton("Gender","Male",true) Female: @Html.RadioButton("Gender","Female") </td></tr>
<tr><td>Course</td><td>@Html.DropDownList("Course")</td></tr>
<tr><td><input type="button" id="btn1" value="Save" /></td></tr>
<tr><td> <div id="msg" style="height:30px;width:100%;z-index:100;background-color:#00ff21;top:0;left:0;position:fixed;display:none;text-align:center;"></div></td></tr>
</table>


<div>
<p>Enter Name @Html.TextBox("name"</p>
<p id="loader" style="display:none;"><img  src="~/Images/kush.gif" style="width:90px;height:100px"/></p>
<div>
<table id="table1" border="1" width="300px">

</table>

</div>
</div>
</body>
</html>

Result:



Note :  Again  we  will discuss same  concept with $.ajax method for save and retrive data but here  we  have to create another controller which name Cetpa………………
Code for CetpaController.cs……………………………………

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AjaxMethodInMvc.Models;

namespace AjaxMethodInMvc.Controllers
{
public class CetpaController : Controller
{
//
// GET: /Cetpa/
testEntities database = new testEntities();
public ActionResult Index()
{
return View();
}

//[HttpPost]
//public JsonResult Save(string RollNo, string Name, string Gender, string Course)
//{

//    try{
//        if (string.IsNullOrEmpty(RollNo))
//        {
//            throw new Exception("Please enter RollNo");
//        }
//        Student ss = new Student
//        {
//            RollNo = Convert.ToInt32(RollNo),
//            Name = Name,
//            Gender = Gender,
//            Course = Course
//        };
//        database.Students.Add(ss);
//        database.SaveChanges();
//        return this.Json(new { result = true, msg = "data save" });
//    }

//    catch (Exception ex)
//    {
//        return this.Json(new { result = false, msg = ex.Message });
//    }
//}

[HttpPost]
public JsonResult Save(Student entity)
{

try
{
if (string.IsNullOrEmpty(entity.RollNo.ToString()))
{
throw new Exception("Please enter RollNo");
}

database.Students.Add(entity);
database.SaveChanges();
return this.Json(new { result = true, msg = "data save" });
}

catch (Exception ex)
{
return this.Json(new { result = false, msg = ex.Message });
}
}


[HttpGet]
public JsonResult GetList(string name)
{
System.Threading.Thread.Sleep(2000);
return this.Json(this.database.Students.Where(obj => obj.Name.StartsWith(name)).ToList(), JsonRequestBehavior.AllowGet);

}
}
}

Code for Index.cshtml
@{
ViewBag.Title = "Index";
}




<h2>Index</h2>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">

$(document).ready(function()

{
$(':button').click(function ()
{
var v = $('#myfrm').serialize();

//var v = { RollNo: $('#RollNo').val(), Name: $('#Name').val(), Gender: $("#Gender").val(), Course: $("#Course").val() };

$.ajax({
type: "POST",
url: "Cetpa/Save",
content: "application/json; charset=utf-8",
dataType: "json",
data: v,
//data: JSON.stringify( v),
success: function (data) {

$('#msg').html(data.msg);
$('#msg').slideDown(1000).delay(2000).fadeOut(1000, function ()
 {

if (data.result)
{
$('#RollNo').val("").focus();
$('#Name').val("");
}
});
},
error: function (data) {


}
});

});



$('#name').keyup(function ()
{
debugger;
var v = $(this).val();
var list = null;
if (v.length >= 2)
{
$('#loader').show();
$.ajax({
type: "GET",
url: "Cetpa/GetList",
data: { name: v },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data)
{
$.each(data, function (i, d)
{
data += "<tr><td>" + d.RollNo + "</td><td>" + d.Name + "</td><td>" + d.Gender + "</td><td>" + d.Course + "</td></tr>";

});

$('#table1').append(data);
},
error: function (response)
{
debugger;
alert('eror');
}

});
}
});

});


</script>

<body>
@using (Html.BeginForm("", "", FormMethod.Post, new { id = "myfrm" }))
{
<table style="margin-top:54px">
<tr><td>RollNo</td><td>@Html.TextBox("RollNo")</td></tr>
<tr><td>Name</td><td>@Html.TextBox("Name")</td></tr>
<tr><td>Gender</td><td>@Html.TextBox("Gender")</td></tr>
<tr><td>Course</td><td>@Html.TextBox("Course")</td></tr>
<tr><td><input type="button" id="btn1" value="Save" /></td></tr>
<tr><td> <div id="msg" style="height:30px;width:100%;z-index:100;background-color:#00ff21;top:0;left:0;position:fixed;display:none;text-align:center;"></div></td></tr>
</table>


<div>
<p>Enter Name @Html.TextBox("name"</p>
<p id="loader" style="display:none;"><img  src="~/Images/kush.gif" style="width:90px;height:100px"/></p>
<div>

<table id="table1" border="1" width="300px">

</table>


</div>
</div>
}
</body>
   



0 comments:

Post a Comment