我有 ASP.NET MVC 2 Web 应用程序。在页面加载时我调用一个 javascript 方法:
function getSomeData() {
$.post(GetTablesDataUrl, null,
function (data) {
alert(data);
});
}
这里调用了我的 HomeController.cs 中的一个方法
public void GetTablesData()
{
WebClient webClinet = new WebClient();
webClinet.DownloadDataAsync( new Uri("http://somer_url"));
webClinet.DownloadDataCompleted += new DownloadDataCompletedEventHandler(webClinet_DownloadDataCompleted);
}
下载完成后,执行下一个方法
void webClinet_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
byte[] responseArray = e.Result;
string s = responseArray.ToString();
ReturnDataToPage(s); // return json object
}
里面是一个将数据返回到我的页面的方法,如下所示
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult ReturnDataToPage(string s)
{
var data = s;
return Json(data);
}
但我总是得到一个空字符串。我做错了什么???
最佳答案
你有两种可能性:
使用普通 Controller ,因为 AJAX 调用已经是异步的,您可能不需要更多:
public class TablesController : Controller { [HttpPost] public ActionResult ReturnTables(string s) { using (var client = new WebClient()) { string result = client.DownloadString("http://example.com"); // Assuming the remote address returns a JSON object // if not parse the response and return Json return Content(result, "application/json"); } } }
使用异步 Controller 和 IOCP(I/O 完成端口):
public class TablesController : AsyncController { [HttpPost] public void ReturnTablesAsync(string s) { AsyncManager.OutstandingOperations.Increment(); var client = new WebClient(); client.DownloadStringCompleted += (sender, e) => { try { AsyncManager.Parameters["result"] = e.Result; } finally { AsyncManager.OutstandingOperations.Decrement(); } }; client.DownloadStringAsync(new Uri("http://www.example.com")); } public ActionResult ReturnTablesCompleted(string result) { // Assuming the remote address returns a JSON object // if not parse the response and return Json return Content(result, "application/json"); } }
在这两种情况下,您都会以相同的方式使用这些操作:
// Not sure exactly what was the purpose of the "s" query string
// parameter as I am not using it in the action
var data = { s: 'some data' };
$.post('<%= Url.Action("ReturnTables", "Tables") %>', data, function(result) {
// Do something with the result
});
这两种方法之间的区别在于,异步版本将使用 I/O 完成端口,并且在检索远程资源期间不会阻止任何工作线程。
关于javascript - 如何在异步方法中返回Json对象以查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5141163/