简体   繁体   English

如何返回Json对象以在Async方法中查看

[英]How to return Json object to view in a Async method


I have ASP.NET MVC 2 web app. 我有ASP.NET MVC 2网络应用程序。 On page load I call a javascript method: 在页面加载时我调用一个javascript方法:

function getSomeData() {
  $.post(GetTablesDataUrl, null,
            function (data) {
               alert(data);
        });
}

here is then called a method in my HomeController.cs 然后在我的HomeController.cs中调用此方法

public void GetTablesData()
{
  WebClient webClinet = new WebClient();
  webClinet.DownloadDataAsync( new Uri("http://somer_url"));
  webClinet.DownloadDataCompleted += new DownloadDataCompletedEventHandler(webClinet_DownloadDataCompleted);
}

when download is completed, next method is executed 下载完成后,执行下一个方法

void webClinet_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
  byte[] responseArray = e.Result;

  string s = responseArray.ToString();

  ReturnDataToPage(s);  // return json object
}

inside is am method to return data back to my page like this inside是am方法将数据返回到我的页面,就像这样

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult ReturnDataToPage(string s)
{
  var data = s;
  return Json(data);
}  

but I always get an empty string. 但我总是得到一个空字符串。 What am I doing wrong??? 我究竟做错了什么???

You have two possibilities: 你有两种可能性:

  1. Use a normal controller and because the AJAX call is already async you probably wouldn't need more: 使用普通的控制器,因为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"); } } } 
  2. Use an async controller and IOCP (I/O Completion Ports): 使用异步控制器和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"); } } 

In both cases you would consume those actions the same way: 在这两种情况下,您都会以相同的方式使用这些操作:

// 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
});

The difference between those two approaches is that the async version would use I/O Completion Ports and wouldn't block any worker threads during the retrieval of the remote resource. 这两种方法之间的区别在于异步版本将使用I / O完成端口,并且在检索远程资源期间不会阻止任何工作线程。

The main issue with your approach is that you are calling the external site ("http://somer_url") asynchronously. 您的方法的主要问题是您异步调用外部站点(“http:// somer_url”)。

This means that the action called by 'someDataDataUrl' (Which, I assume, is not shown in your question) will return immediately, and this is probably before the asynch call returns with your actual data. 这意味着'someDataDataUrl'调用的操作(我假设,在你的问题中没有显示)将立即返回,这可能是在异步调用返回实际数据之前。

The secondary issue (If my understanding of your - possibly mistyped - question is correct) is that when the asynch call handler is invoked, it calls 'ReturnDataToPage' (Should this be 'ReturnTables'?), and then does nothing with the JsonResult that it gets. 第二个问题(如果我对你的理解 - 可能是错误的 - 问题是正确的)是,当调用异步调用处理程序时,它调用'ReturnDataToPage'(这应该是'ReturnTables'?),然后对JsonResult不执行任何操作它得到了。

You would be better off calling the external site Synchronously (although this introduces block issues, so timeouts need to be introduced) and the returning the result of this call correctly. 最好是同步调用外部站点(虽然这会引入块问题,因此需要引入超时)并正确返回此调用的结果。

Doing this, however, would entail a bit of extra research (Not something that I've done from .NET, I'm afraid) 但是,这样做需要进行一些额外的研究(不是我从.NET做过的,我担心)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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