2012-12-17 216 views
1

我面臨着以下問題:MVC 4路由,GET/POST請求處理

我有一個控制器,可以說以下操作:

 [HttpGet] 
     public ActionResult Index() 
     { 
      var viewModel = new IndexViewModel(); 

      return View("Index", viewModel); 
     } 



     [HttpPost] 
     public void ExportToExcell(LeadsViewModel model) 
     { 
      // Export to excell code goes here 
     } 

的問題如下:

索引頁

用戶輸入這個網址:/控制器/索引

然後用戶提交表單行動ExportToExcel

數據導出到Excel(文件下載),沒關係。

的URL將變爲/控制器/ ExportToExcell

然後當我點擊「回車」我要去/控制器/ ExportToExcell但GET 當然與頁面下降,並沒有發現,但問題是如何正確地通過此項交易在MVC

+0

你能分享你的ExportToExcell行動? (這不是你的問題,我想用這樣的東西,我寫了一個導出動作,但是我的工作不正常,如果你的工作正常,我可以使用它)。 –

+0

它是我們團隊開發的來自第三方dll的代碼。它是創建XML文件,Excel可以讀取它 – StringBuilder

回答

4

不要使用void返回的類型你的帖子的動作,使用ActionResult

[HttpPost] 
public ActionResult ExportToExcell(LeadsViewModel model) 
{ 
    // Export to excell code goes here 
    return RedirectToAction("Index"); 
} 
+0

是返回視圖(「SomeView」,viewModel)也是不好的做法,因爲事情會發生......我meam我有行動稱爲富(){返回視圖(「索引」 ,新的ViewModel()}我總是需要使用適合路由名稱的返回視圖(viewModel),並在其他情況下使用RedirectToAction – StringBuilder

+0

@StringBuilder你應該爲谷歌PRG(POST-REDIRECT-GET)模式,這是非常有趣的...在MVC應用程序中一個非常好的主意(我的觀點)。請參閱http://blog.jorritsalverda.nl/2010/03/10/maintainable-mvc-post-redirect-get-pattern/ –

+0

謝謝男人,我會讀這個。 – StringBuilder

2

我相信你的問題是,你不回一個FileResult,瀏覽器將把你重定向到你的發佈路徑。目前無法對其進行測試,但我認爲以下內容應該可以工作。

[HttpPost] 
public ActionResult ExportToExcell(LeadsViewModel model) 
{ 
    // Generate the Excel file into a MemoryStream for example 

    // Return a FileResult with the Excel mime type 
    return File(fileStream, "application/vnd.ms-excel", "MyExcelFile.xls"); 
} 

檢查FileResultController.File的更多細節。

作爲一個說明,我不能完全肯定,如果這是一個Excel文件的MIME類型,但如果你說你已經下載的文件,你可能已經擁有它:)

0

您必須返回的ActionResult而不是無效的。

public ActionResult ExportToExcel(PagingParams args) 
    { 
     var data = new StudentDataContext().Student.Take(200).ToList(); 
     return data.GridExportToExcel<Student>("GridExcel.xlsx", ExcelVersion.Excel2007, args.ExportOption); 
    } 

請檢查鏈接:Export Action

相關問題