Using jQuery in Asp. Net MVC Architecture is easy, while using jQuery to implement Ajax is easier. After the Asp. Net MVC framework is generated, the jQuery script is included. For environment settings, see my other article: Asp. Net MVC instance. Here, we still use the environment in the instance. You can see the jQuery script in the Scripts folder of the generated framework.
Create a function in TestModel. cs to obtain Json data. The Tets table is still used and contains two fields: Id and Name.
The Code is as follows:
// 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, in short, is data in the form of a Key-Value array. Then, create a controller by default. The generated controller has only one method: Index (). Create another method for jQuery to call. The completed Code is as follows: JQueryController. cs. Note: In MVC2.0, jQuery is prohibited from calling server data by default. Therefore, you must add the access permission JsonRequestBehavior. AllowGet in the code.
The Code is as follows:
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 );
}
}
}
Right-click Index () and generate a view based on the default options. You can view the generated code in Views/JQuery: Index. aspx: The generated code is very simple. We can insert the Script code as follows:
The Code is as follows:
<% @ Page Title = "" Language = "C #" MasterPageFile = "~ /Views/Shared/Site. Master "Inherits =" System. Web. Mvc. ViewPage "%>
JQuery