After generating the Asp.Net MVC framework, the jQuery script has been included. For related environment settings, please refer to my other article: Asp.Net MVC Example. Here, we still rely on the environment in the instance. The jQuery script can already be seen in the Scripts folder in the generated framework.
We create a function in TestModel.cs to obtain Json data, still using the Tets table, containing two fields: Id and Name.
//JsonDataArray
public static Array GetJsonArray(String name)
{
Array data = null;
try
{
data = (from c in testDb.test
where c.name.Contains(name)
select new { c.id, c.name }).ToArray();
}catch(ArgumentNullException ae)
{}
return data;
}
Json Data, simply put, is data in the form of a Key-Value array. Then create a controller according to the default options. The generated controller has only one method: Index(). We create another method for jQuery to call. The completed code is as follows: JQueryController.cs. Note: jQuery is prohibited from calling server data by default in MVC2.0, so you must add access permissions in the code: JsonRequestBehavior.AllowGet.
using System;
using System.Collections.Generic ;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcWeb.Models;
namespace MvcWeb.Controllers
{
public class JQueryController : Controller
{
//
// GET: /JQuery/
public ActionResult Index()
{
return View();
}
public JsonResult FindByName(string name)
{
return Json(TestModel.GetJsonArray(name), JsonRequestBehavior.AllowGet);
}
}
}
Then right-click on Index() and use the default options to generate a view. You can see the generated code in Views/JQuery: Index.aspx. The generated code is very simple. We then insert the Script code and complete it as follows:
<%@ Page Title="" Language="C#" MasterPageFile= "~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
JQuery