I'm having trouble posting date value from MVC Razor view to MVC Controller
HTML
@using (Html.BeginForm("MainframeFilingDetail", "Report", FormMethod.Post, htmlAttributes: new { @class = "form-inline", id = "formDetails" }))
{
<div class="form-group">
<label id="ReportBeginDate">Report Begin Date</label>
<input type="date" id="BeginDate" value="@DateTime.Today.ToString("yyyy-MM-dd")"/>
</div>
<div class="form-group">
<label id="ReportEndDate">Report End Date</label>
<input type="date" id="EndDate" value="@DateTime.Today.ToString("yyyy-MM-dd")"/>
</div>
<input id="submit" type="submit" value="Submit" class="btn btn-primary pull-right"/>
}
MVC Controller
[HttpPost]
public ActionResult MainframeFilingDetail(DateTime beginDate, DateTime endDate)
{
var isValidDate = ValidateDate(beginDate, endDate);
if(!isValidDate)
{
ModelState.AddModelError("", "Invalid Date!");
}
var mainframeData = GetMainframeData();
return View(mainframeData);
}
Question
When I click the submit button I get exception although I have default value in date input type. I cannot have null values passed to the controller.
The parameters dictionary contains a null entry for parameter
'beginDate' of non-nullable type 'System.DateTime' for method
'System.Web.Mvc.ActionResult MainframeFilingDetail(System.DateTime,
System.DateTime)' in
'SOS.BusinessFilings.Web.Int.Controllers.ReportController'. An
optional parameter must be a reference type, a nullable type, or be
declared as an optional parameter. Parameter name: parameters
Best Answer
What I did (and worked well) was to parse the date into timestamp format (13 digits that represent a date). Then, sent it as a string (.toString()) and it solved the problem.