MVC RedirectToAction 和 XMLHttpRequest 发送
我有一个可以包含文件的表单,它成功地显示了进度条。我的问题是,在 MVC 控制器中,我有:
return RedirectToAction("Complete", new { title = title });
如果我单步执行,它会执行 Complete 方法,但随后会返回到 JavaScript 加载事件,并且不会重定向我,除非我在加载事件侦听器中添加 JavaScript 重定向(uploadComplete ):
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/Submit-Recipe", true);
xhr.send(fd);
function uploadComplete(evt) {
//var valueFromController = how do I get a value here?;
//window.location.replace("http://@ConfigurationManager.AppSettings["website"]/SubmitRecipeComplete/" + valueFromTheController);
}
有没有办法不必添加 JavaScript 重定向?如果我确实需要 JavaScript 重定向,当变量需要是 ActionResult 时,如何从控制器传回变量(如果出现错误并且我需要重新显示页面?)。
我可以通过添加第二个页面来解决这个问题,我可以在其中知道“valueFromController”,但 2 个表单会稍微破坏工作流程。
编辑
我按照 Praveen 所说的做了,但是 GetData() 对我不起作用,所以我用了这个:
evt.currentTarget.responseText
为了确定是否返回视图或内容,我在 xhr.send(fd); 之前添加了这个;
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
在控制器中我可以执行以下操作:
if (Request.IsAjaxRequest())
{
return Content(title);
}
I have a form which can contain files and it shows a progress bar successfully. My problem is that in the MVC Controller I have:
return RedirectToAction("Complete", new { title = title });
This goes and executes the Complete method if I step through but it then goes back to the JavaScript load event and does not redirect me unless I add a JavaScript redirect in the load event listener (uploadComplete):
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/Submit-Recipe", true);
xhr.send(fd);
function uploadComplete(evt) {
//var valueFromController = how do I get a value here?;
//window.location.replace("http://@ConfigurationManager.AppSettings["website"]/SubmitRecipeComplete/" + valueFromTheController);
}
Is there a way to not have to add a JavaScript redirect? If I do need a JavaScript redirect, how can I pass a variable back from the controller when it needs to be an ActionResult (for if there is an error and I need to redisplay the page?).
I can work around this by adding a second page where I could know the "valueFromController" but 2 forms breaks the workflow a bit.
EDIT
I did what Praveen said but GetData() did not work for me so I used this instead:
evt.currentTarget.responseText
To determine if to return the View or Content I added this just before xhr.send(fd);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
In the controller I can then do:
if (Request.IsAjaxRequest())
{
return Content(title);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)