2016-04-30 130 views
0

無效項我堅持一個奇怪的行爲..我有它返回Excel文件的操作:再次..參數字典包含參數

public ActionResult AgentPortfolioReport(DateTime fromDate, DateTime toDate) 
    { 
     ... 

     return File(ms.ToArray(), "application/vnd.ms-excel", "SomeReport.xlsx"); 
    } 

然後我把我的觀點:

@Html.ActionLink("Get Report", "AgentPortfolioReport", new { fromDate = DateTime.Today.AddDays(-15), toDate = DateTime.Today }, new { @class = "iin-submit", id = "loadPortfolio" }) 

一切正常,文件被下載。然後可變日期開始發揮作用。我嘗試使用一個乾淨的JavaScript與功能:

function LoadReport(action, fromDate, toDate) { 
     window.location = '/Reports/' + action + '?fromDate=' + encodeURIComponent(fromDate) + '&toDate=' + encodeURIComponent(toDate); 
    } 

和繁榮!我得到一個異常:

The parameters dictionary contains a null entry for parameter 'toDate' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.ActionResult AgentPortfolioReport(System.DateTime, System.DateTime)' in 'AgentsNetwork.Controllers.ReportsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. 
Parameter name: parameters 

我也試過用這樣的形式來解決它:

@using (Html.BeginForm("AgentPortfolioReport", "Reports", FormMethod.Get)) 
{ 
    <div> 
    Укажите период:<br/> 
    <label for="fromDate">C </label> 
    <input id="fromDate" name="fromDate" type="text" /> 
    <label for="toDate"> по </label> 
    <input id="toDate" name="toDate" type="text" /> 
    </div> 
    <p> 
    <input type="submit" value="Get report" /> 
    </p> 
} 

但結果是一樣的。添加可空的id參數沒有幫助。請給我一個提示有什麼問題..

+0

當不例外發生?表單發佈後?另外,您是否使用任何自定義模型粘合劑? – newmanth

+0

@newmanth請求甚至不會執行任何操作。所以當我點擊一個按鈕時,我得到了這個錯誤。沒有自定義模型聯編程序是用戶。奇怪的是,與Acitonlink一切正常.. – IDeveloper

+0

所以,我認爲你的問題可能是全球化的設置。你的日期條目是什麼格式?例如,您是使用「30.4.2016」還是「30/4/2016」或其他? – newmanth

回答

0

默認情況下,MVC在其模型活頁夾中使用不變文化。不幸的是,如果你提供了一個不匹配的日期/時間格式的文件夾,這會導致DateTime解析器中斷。爲了克服這個問題,你可以創建像這樣一個自定義的模型綁定,改變了culture code酌情:

using System; 
using System.Globalization; 
using System.Web.Mvc; 

public class DateTimeBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     return value.ConvertTo(typeof(DateTime), new CultureInfo("ru-RU")); 
     } 
    } 
} 

以下兩行添加到您的Application_Start()方法Global.asax.cs

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder()); 
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder()); 
+0

這不能解決OP的問題,這就是爲什麼值爲null的原因 - 如果日期是以不同於服務器的格式發送的文化和綁定失敗,屬性的值將是'1/1/0001'(不是'null',並且不會有任何例外) –

+0

這不是事實,我自己對它進行了驗證。如果日期以不同於應用程序文化的格式輸入,則會引發運行時異常。例如,如果您要輸入30.4.2016(對於不變的文化,但是有效的俄語日期格式無效),則默認聯編程序將失敗並引發異常。但是,如果您添加上面的自定義綁定,值正確傳遞。 – newmanth

+0

OP聲稱讓參數爲空可以拋出錯誤,所以格式/文化沒有區別。這不是OP的問題。 –

相關問題