Use
JSON and MVC 4.0 to Retrieve Data from Database with Entity Frame Work
Next Topic
create database MvcwithJquery
Next Topic
This
blog post describes how you can implement an MVC model controller and action to
retrieve data from database with JSON. ASP.NET MVC
makes it very easy to implement action methods that generate JSON. To do so,
simply create an action in a controller and use the Json() method to return
data
--Execute in Sql Server
create database MvcwithJquery
use MvcwithJquery
create table Student(RollNo int primary key,Name varchar(50),Gender varchar(50),Course varchar(50))
insert into Student values(1,'Kush Tiwari','Male','Mca')
Note : Frirst we
take Asp.Net Mvc 4.0 Web Application and select Basic with Razor View Engine
because when select Basic you find script folder in your Application by
Default
//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.js"></script>
@* javascript code*@
<script type="text/javascript">
$(document).ready(function ()
{
var path = "/Home/display";
$("#btnSearch").click(function ()
{
debugger;
var n = $("#txtsrno").val();
$.getJSON(path, { RollNo: n
}, function (data)
{
if (data != null)
{
var d = "SrNo=" + data.RollNo + "</br>Name=" + data.Name + "</br>Gender=" + data.Gender + "</br>Course=" + data.Course;
$("#showdata").html(d);
}
else
{
document.write("Not
Found");
}
});
});
});
</script>
</head>
<body>
<div>
<table width="auto" >
<tr><td colspan="2"><b>Use JSON and MVC 4.0
to Retrieve Data from Database with Entity Frame Work</b></td></tr>
<tr><td>Search with SrNo</td><td>@Html.TextBox("txtsrno")</td></tr>
<tr><td></td><td> <input type="button" id="btnSearch" value="Submit" /></td></tr>
<tr><td colspan="2"> <span id="showdata" ></span></td></tr>
</table>
</div>
</body>
</html>
Code for HomeController.cs………………………………………………………….
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using
MvcApplicationwithJquery.Models;
namespace
MvcApplicationwithJquery.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
//create instance of
Entities...............................
MvcwithJqueryEntities mm = new MvcwithJqueryEntities();
public ActionResult Index()
{
return View();
}
//create method display…………………………….
public JsonResult display(string rollno)
{
int i = Convert.ToInt32(rollno);
var v = mm.Students.Where(m
=> m.RollNo == i).Select(m => new { RollNo = m.RollNo, Name = m.Name,
Course = m.Course, Gender = m.Gender }).FirstOrDefault();
return Json(v, JsonRequestBehavior.AllowGet);
}
}
}
very nice...sir..
ReplyDeletevar path = "/Home/display"; --- why we use this line??
ReplyDeleteI try to this not work
ReplyDelete