簡體   English   中英

從Javascript調用ASP.NET C#控制器方法

[英]Call ASP.NET C# Controller Method from Javascript

我在javascript文件中有一個var toto。 我想調用一個C#控制器方法,該方法返回一個字符串,然后將結果字符串分配給toto。
我嘗試了一些方法來實現這一目標,但似乎沒有任何效果。
有人可以解釋給我最簡單的方法嗎? 這是Windows Azure項目。

非常感謝 !

您可以使用AJAX。 例如,使用jQuery時,您可以使用$.getJSON方法向AJAX請求發送頂部的控制器操作,該操作將返回JSON編碼的結果,並且在成功回調中使用結果:

$.getJSON('/home/someaction', function(result) {
    var toto = result.SomeValue;
    alert(toto);
});

和控制器動作:

public ActionResult SomeAction() 
{
    return Json(new { SomeValue = "foo bar" }, JsonRequestBehavior.AllowGet);
}

您必須使用JSON:

控制者

public class PersonController : Controller
{
   [HttpPost]
   public JsonResult Create(Person person)
   {
      return Json(person); //dummy example, just serialize back the received Person object
   }
}

Java腳本

$.ajax({
   type: "POST",
   url: "/person/create",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: jsonData,
   success: function (result){
      console.log(result); //log to the console to see whether it worked
   },
   error: function (error){
      alert("There was an error posting the data to the server: " + error.responseText);
   }
});

了解更多: http : //blog.js-development.com/2011/08/posting-json-data-to-aspnet-mvc-3-web.html#ixzz1wKwNnT34

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM