簡體   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