简体   繁体   中英

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. 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. This is the bit I am struggling with, as I am new to AJAX calls.

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. 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)

[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?

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.

Note that when retrieving data then a GET request should be made, not a 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. 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"
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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