我想从.net MVC上的文件中引用一个json。JSON 位于"内容文件"下。我该怎么做?(这里的例子不起作用。
var url1 = "../../Content/FreeJsonPL.json";
$.getJSON(url1, function (data2) {}
谢谢!!
您需要编写控制器才能从服务器获取文件 下面是一个将返回 Json 结果的示例。在下面的代码中,您需要解析 Json 文件,例如 GetUsersHugeData 函数中的 Usermodel
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using JsonResultDemo.Models;
namespace JsonResultDemo.Controllers
{
public class JsonDemoController : Controller
{
/// <summary>
/// Get the huge list of Users
/// </summary>
/// <returns></returns>
public JsonResult GetUsersHugeList()
{
var users = GetUsersHugeData();
return Json(users, JsonRequestBehavior.AllowGet);
}
/// <summary>
/// Get the huge list of users
/// </summary>
/// <returns></returns>
private List<UserModel> GetUsersHugeData()
{
var usersList = new List<UserModel>();
UserModel user;
for (int i = 1; i < 51000; i++)
{
user = new UserModel
{
UserId = i,
UserName = "User-"+i,
Company = "Company-"+i
};
usersList.Add(user);
}
return usersList;
}
/// <summary>
/// Override the Json Result with Max integer JSON lenght
/// </summary>
/// <param name="data">Data</param>
/// <param name="contentType">Content Type</param>
/// <param name="contentEncoding">Content Encoding</param>
/// <param name="behavior">Behavior</param>
/// <returns>As JsonResult</returns>
protected override JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}
#endregion
}
}
然后你需要编写你的获取请求客户端代码
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://domain_name/api/controller_name/method_name", false);
xhr.send();