Home >Web Front-end >JS Tutorial >Example code for easily implementing Ajax using jQuery_jquery

Example code for easily implementing Ajax using jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 18:21:15909browse

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.

Copy code 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, 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.
Copy 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);
}
}
}

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:
Copy code The code is as follows:

<%@ Page Title="" Language="C#" MasterPageFile= "~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

JQuery




Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn