An AJAX request. Example of using Json
Mvc uses JsonResult to return Json data
<控制器>
Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; using System. configuration; using System. data. sqlClient; using System. data; using JSON. models; namespace JSON. controllers {public class HomeController: Controller {public ActionResult Index () {return View ();}////// Get the age /////////
Returns a string.
Public ActionResult GetAge (string username) {var age = ""; if (! String. isNullOrWhiteSpace (username) {string SQL = "select Age from t_user where UserName = @ username"; age = (SqlHelper. executeScalar (SQL, new SqlParameter ("username", username ))). toString () ;}return Content (age );}////// Get the name /////////
Method to return the Json object of a Table
Public ActionResult GetName (int id) {string SQL = "select * from t_user where id = @ id"; DataTable dt = SqlHelper. executeDataTable (SQL, new SqlParameter ("id", id); var data = DataTableToJson. toJson (dt); // call the ToJson method of the DataTableToJson class to convert the table on the dt side to the Json format. // Type type = data. getType (); the data type is actually a string type through type debugging. Return new JsonResult // return a JsonResult object {Data = new {MyData = data }, // assign the Json-Format String data to the MyData attribute of the JsonResult object (this attribute name can be set by yourself) JsonRequestBehavior = JsonRequestBehavior. allowGet // allow http get requests from the client };}}}
<视图>
<% @ Page Language = "C #" Inherits = "System. Web. Mvc. ViewPage
"%>
Index<Script src = ".../Scripts/jquery-1.7.1.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript"> $. ajax ({url: "/Home/GetAge", type: "get", // async: true, dataType: "json", data: {username: ""}, success: function (ajaxData) {$ ("# div1 "). text (ajaxData) ;}}); </script> <script type = "text/javascript" >$ (function () {$ ("# btnClick "). click (function () {$. ajax ({url: "/Home/GetName", dataType: "json", type: "get", data: {id: "1"}, success: function (Dbdata) {// Debugger; if you want to debug it, you can write it here and it will jump here when you execute the debugger. Then press F10 to execute // console. log ('dbdata', Dbdata); // output the log var str = Dbdata in the browser console. myData; // obtain the Json string whose key is MyData // console. log ('str', str); var obj = eval ('+ str + ')'); // convert str Json string to an object // console. log ('obj ', obj); // alert ('username:' + obj. userName); $ ("# div2 "). text (obj. userName) ;}})}) </script>
SQLHelper
Using System; using System. collections. generic; using System. linq; using System. text; using System. configuration; using System. data. sqlClient; using System. data; using System. reflection; namespace JSON. controllers {public class SqlHelper {////// Obtain the database connection string ///Private static string connStr = ConfigurationManager. ConnectionStrings ["ConnStr"]. ConnectionString ;////// Execute the query and return the query result as a DataTable //////SQL statement to be executed///SQL statement Parameters///
The returned value is a DataTable.
Public static DataTable ExecuteDataTable (string SQL, params SqlParameter [] parameters) {using (SqlConnection conn = new SqlConnection (connStr) {conn. open (); // another method, which is a little different from the preceding methods using (SqlCommand cmd = new SqlCommand (SQL, conn) {cmd. parameters. addRange (parameters); DataTable dt = new DataTable (); using (SqlDataAdapter adapter = new SqlDataAdapter (cmd) {adapter. fill (dt); return dt ;}}}}}