如何将输入类型日期POST到MVC控制器

时间:2017-02-18 00:02:24

标签: asp.net-mvc html5 twitter-bootstrap razor

我无法将日期值从MVC Razor视图发布到MVC控制器

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控制器

[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);
}

问题

当我点击提交按钮时,虽然我在日期输入类型中有默认值,但我得到了异常。我不能将空值传递给控制器​​。

  

参数字典包含参数的空条目   &#39; BEGINDATE&#39;非可空类型的System.DateTime&#39;方法   &#39; System.Web.Mvc.ActionResult MainframeFilingDetail(System.DateTime,   的System.DateTime)&#39;在   &#39; SOS.BusinessFilings.Web.Int.Controllers.ReportController&#39 ;.一个   可选参数必须是引用类型,可空类型或be   声明为可选参数。参数名称:参数

2 个答案:

答案 0 :(得分:0)

我所做的(并且工作得很好)是将日期解析为时间戳格式(代表日期的13位数字)。然后,将其作为字符串(.toString())发送,即可解决问题。

答案 1 :(得分:0)

它的价值(我是新手,所以希望这对某人有帮助)。 我正在使用MVC网站在Visual Studio中工作,并使用razor,c#和HTML 5

我有点想让日期输入元素正常工作。
我需要显示通过模型传递到视图中的日期,并返回日期(如果用户输入/修改了该日期)。最重要的是,日期是List属性的一部分。另外,它被定义为nullabel DateTime(DateTime?)

这是视图代码的一部分,它最终使我不仅可以显示传入的日期,还可以将日期正确地发布到下一个控制器操作:

@for (int i = 0; i < Model.CurrentRoles.Count; i++)
{
    <tr>
        <td>
            @Html.HiddenFor(m => m.CurrentRoles[i].Id)
            @Html.HiddenFor(m => m.CurrentRoles[i].Name)
            @Model.CurrentRoles[i].Name
        </td>
        <td>
            @{ string sdateValue = Model.CurrentRoles[i].StartDate == null ? "" : ((DateTime)(Model.CurrentRoles[i].StartDate)).ToString("yyyy-MM-dd"); }
            <input type="date" name="CurrentRoles[@i].StartDate" value="@sdateValue" />
        </td>
        <td>
            @{ string edateValue = Model.CurrentRoles[i].EndDate == null ? "" : ((DateTime)(Model.CurrentRoles[i].EndDate)).ToString("yyyy-MM-dd"); }
            <input type="date" name="CurrentRoles[@i].EndDate" value="@edateValue" />
        </td>
    </tr>
}