我正在创建 mvc 4 应用程序,在其中使用 ajax 从 js 文件调用 Controller 中的函数。
当我从ajax调用该函数时,它正确地调用了相应的函数。但成功函数和错误函数都没有触发。有人可以帮我纠正我的错误吗?
我想从数据库读取数据,将其转换为 json 格式并将其写入 .js 文件,然后触发成功函数。帮我解决这个问题。提前致谢。
这是我的代码。
$.ajax({
//url: '@Url.Action("getJsonData","Home")',
url: "Home/getJsonHugeData1",
//data: "{}",
type: "GET",
//contentType: 'application/json',
//dataType: "json",
success: function () {
alert();
alert('success getJsonHugeData');
loaddata(data);
},
error:function(){
alert('error');
}
});
Controller :
public JsonResult getJsonHugeData()
{
var users = GetUsersHugeData();
string json = "var dataSource=";
json += JsonConvert.SerializeObject(users.ToArray());
System.IO.File.WriteAllText(Server.MapPath("/Scripts/NewData.js"), json);
return Json(users, JsonRequestBehavior.AllowGet);
}
private List<UserModel> GetUsersHugeData()
{
var usersList = new List<UserModel>();
UserModel user;
List<dummyData> data = new List<dummyData>();
using (Database1Entities dataEntity = new Database1Entities())
{
data = dataEntity.dummyDatas.ToList();
}
for (int i = 0; i < data.Count; i++)
{
user = new UserModel
{
ID = data[i].Id,
ProductName = data[i].ProductName,
Revenue = data[i].Revenue,
InYear = data[i].InYear.Year
};
usersList.Add(user);
}
}
最佳答案
我相信您的浏览器会阻止通过ajax下载的文件,这是因为JavaScript无法与磁盘交互。如果您想使其正常工作,则必须使用表单帖子来实现。
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "DownloadForm" }))
{
... form data would be here if you had any...
<button type="submit">Download</button>
}
然后,您将返回一个 FileStreamResult,其中包含要下载的文件的内容。
public ActionResult Action(FormModel model)
{
// Do work to get data for file and then return your file result to the browser.
return new FileStreamResult(new MemoryStream(fileData), "text/csv") // set the document type that is valid for your file
{
FileDownloadName = "users.csv"
};
}
关于javascript - .net mvc 4应用程序-从ajax调用 Controller 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35079544/