2013-04-27 60 views
0

我正在尋找一種方法來通過表單發佈後保留url參數。例如,我的GET方法需要一個字符串「type」,並使用它來確定要在視圖中呈現的報告的類型。網址如下:MVC如何傳遞網址值以及模型從動作到視圖

http://mysite/Reports/Report?type=1 

    [HttpGet] 
    public ActionResult Report(string type) 
     { 
     var model = new ReportsModel() 
      { 
      Report = ReportList.Find(o => o.ReportType == type) 
      }; 

      return View(model);    
     } 

視圖已經有開始用於確定日期的日期範圍/結束日期過濾器來顯示報告的類型形式:

@using (Html.BeginForm("Report", "Reports")) 
    { 
     Report.ReportName 
     @Html.HiddenFor(o => o.Report.ReportType) 
     @Html.EditorFor(o => o.Report.StartDate)<br/> 
     @Html.EditorFor(o => o.Report.EndDate)<br/> 
     <button id="reports">Report</button> 
    } 

上述表單發佈到根據指定的報告類型,開始/結束日期從數據庫獲取報告數據並返回到視圖的操作。

[HttpPost] 
     public ActionResult Report(GenericReportsModel model) 
     { 
      switch (model.Report.ReportType) 
      { 
       case ReportType.ReportType1: 
        model.Result = ReportRepository.GetReport<ReportType1>(model.StartDate, model.EndDate); 
        break; 
       case ReportType.ReportType2: 
        model.Result = ReportRepository.GetReport<ReportType2>(model.StartDate, model.EndDate); 
        break;      
      }  
      return View(model); 
     }   

問題是,在發佈之後,「type」參數從url中丟失。

Before the post: http://mysite/Reports/Report?type=1 
After the post: http://mysite/Reports/Report 

我需要能夠做這樣的事情(不工作):

return View(model, new {ReportType = model.ReportType); 

我如何保存類型參數的URL後門柱,萬一有人想複製並粘貼網址發送給其他人?

回答

0

您需要更新Html.BeginForm和您的HttpPost版本的Report方法。

@using(Html.BeginForm("Report", "Report", "YourController", new { type = model.ReportType}) 
{ 
    // I am assuming that model.ReportType == type argument 
    // in your HttpGet Report action 

    // The rest of the form goes here 
} 

你的行動應該是這樣的:

[HttpPost] 
public ActionResult Report(string type, GenericReportsModel model) 
{ 
    switch (model.Report.ReportType) 
    { 
     case ReportType.ReportType1: 
      model.Result = ReportRepository.GetReport<ReportType1>(model.StartDate, model.EndDate); 
      break; 
     case ReportType.ReportType2: 
      model.Result = ReportRepository.GetReport<ReportType2>(model.StartDate, model.EndDate); 
      break;      
    }  
    return View(model); 
} 

如果type不等於model.ReportType,那麼你應該創建一個包含從GenericsReportModel和這個其他報告類型值的視圖模型。

相關問題