0
可選打開一個新的窗口,在ASP.Net MVC 2應用程序,我要做到以下幾點:在處理一個表單提交的動作我想:在控制器動作
- 將用戶重定向到其他視圖在當前的瀏覽器窗口
- 打開表示其他信息的新窗口(其它視圖)
即可以容易地進行設置的形式的元素的屬性target="_blank"
和加入以下jQuery腳本:
$(function() {
$("form").submit(function() {
window.location = "...";
});
});
由操作處理程序返回的視圖將在窗體發佈到的新窗口中呈現。
但是,讓我們把它有點麻煩:
- 如果在執行操作時沒有服務層錯誤,然後做以上。
- 如果在執行動作時有任何服務層錯誤,則不要打開新窗口,並且動作返回的視圖必須顯示在窗體所在的窗口中。
例如:假設服務層生成一個pdfDocument以向用戶顯示一切是否正常,並且該pdf必須顯示在新窗口中。
[HttpPost]
public ActionResult SomeAction(FormCollection form)
{
var serviceMethodParams = ... // convertion from the form data somehow
MemoryStream pdfDocument = null;
if (!serviceLayer.DoSomething(serviceMethodParams, out pdfDocument))
{
// Something went wrong, do not redirect, do not open new window
// Return the same view where error should be displayed
return View(...);
}
// The service method run ok, this must be shown in a new window and the origal window must be redirected somewhere else
return File(pdfDocument.ToArray(), "application/pdf");
}
注意,當服務返回true
,但如果服務返回false
顯示錯誤的視圖顯示在一個新窗口並被重定向別處原來的窗口最初的解決方案做工精細。