繁体   English   中英

如何从 controller 传递数据以在 MVC 中的 JQuery AJAX 调用期间查看?

[英]How to pass data from a controller to view during a JQuery AJAX call in MVC?

在我看来,我有一个 AJAX 调用,它向我的 controller 发送一个 id 参数。 这一点工作正常。 在我的 controller 中,我计划使用该 ID 查询数据库,提取相关数据并将其发送回 AJAX 调用/视图。 这是我正在努力解决的问题,因为我是 AJAX 呼叫的新手。

var chosenSchoolID = $("#SelectedSchoolId").val();

$.ajax({
  url: "/Home/GetSchoolDetailsAJAX",
  type: "POST",
  data: {
    schoolID: chosenSchoolID
  },
  dataType: "text",
  success: function(data) {
    if (data == "success") {

    }
  },
  error: function(data) {
    if (data == "failed")
      alert("An error has occured!");
  }
});

以上是我的 AJAX 调用,这确实符合我的 controller 方法。 但是在我的 controller 中,我现在想发回其他字符串数据,但我不确定如何执行此操作(目前只是占位符代码)

[HttpPost]
public ActionResult GetSchoolDetailsAjax(string schoolID)
{
  // query database using schoolID
  // now we have other data such as:
  string SchoolName = "";
  string SchoolAddress = "";
  string SchoolCity = "";
  return null;
}

我必须在 Jquery 中声明变量并传递到 AJAX 调用的数据参数中才能传递值吗?

提前谢谢了

最简单的方法是使用 controller 中的return Json()从数据库中检索到的实体。

请注意,在检索数据时,应该发出 GET 请求,而不是 POST。 此外,默认的 MVC 配置应该设置路由以允许您在 URL 中提供所需资源的id 因此,试试这个:

$.ajax({
  url: "/Home/GetSchoolDetailsAJAX/" + $("#SelectedSchoolId").val(),
  type: "get",
  success: function(school) {
    console.log(school);
  },
  error: function() {
    alert("An error has occured!");
  }
});
[HttpGet]
public ActionResult GetSchoolDetailsAjax(string id) {
  var school = _yourDatabaseContext.Schools.Single(s => s.Id == id); // assuming EF
  return Json(school);
}

如果您想在没有数据库集成的情况下对此进行测试,请修改以下行:

var school = new {
  Id = id,
  Name = "Hogwarts",
  Address = "Street, City, Country"
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM