简体   繁体   English

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

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

In my view, I have an AJAX call which sends an id parameter to my controller.在我看来,我有一个 AJAX 调用,它向我的 controller 发送一个 id 参数。 This bit works fine.这一点工作正常。 In my controller, I plan to query the database with that id, pull out associated data and want to send this back to the AJAX call/view.在我的 controller 中,我计划使用该 ID 查询数据库,提取相关数据并将其发送回 AJAX 调用/视图。 This is the bit I am struggling with, as I am new to AJAX calls.这是我正在努力解决的问题,因为我是 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!");
  }
});

The above is my AJAX call, and this does hit my controller method.以上是我的 AJAX 调用,这确实符合我的 controller 方法。 However in my controller, I want to now send back other string data and I am unsure on how to do this (just placeholder code currently)但是在我的 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;
}

Must I declare variables in my Jquery and pass into the data parameter of the AJAX call in order for the values to be passed?我必须在 Jquery 中声明变量并传递到 AJAX 调用的数据参数中才能传递值吗?

Many thanks in advance提前谢谢了

The simplest way to do this is to return the entities retrieved from your database using return Json() from your controller.最简单的方法是使用 controller 中的return Json()从数据库中检索到的实体。

Note that when retrieving data then a GET request should be made, not a POST.请注意,在检索数据时,应该发出 GET 请求,而不是 POST。 In addition the default MVC configuration should have the routes setup to allow you to provide the id of the required resource in the URL.此外,默认的 MVC 配置应该设置路由以允许您在 URL 中提供所需资源的id As such, try this:因此,试试这个:

$.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);
}

If you'd like to test this without the database integration, amend the following line:如果您想在没有数据库集成的情况下对此进行测试,请修改以下行:

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