我想从.net MVC上的文件中引用json。 JSON位于内容文件下。 我怎样才能做到这一点? (这里的例子不起作用..)
var url1 = "../../Content/FreeJsonPL.json";
$.getJSON(url1, function (data2) {}
谢谢!
答案 0 :(得分:0)
您需要编写控制器以从下面的服务器获取文件是一个返回Json结果的示例。在下面的代码中,您需要在GetUsersHugeData函数中解析像Usermodel这样的Json文件
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();