【问题标题】:MVC ajax form submission returns default date of DateTime propertyMVC ajax 表单提交返回 DateTime 属性的默认日期
【发布时间】:2016-01-28 13:53:27
【问题描述】:

我正在使用下面的 Ajax 表单来选择和发布日期范围。

查看模型:

public class ViewFormSubmissionsVM
    {
        public string FormName { get; set; }
        public Guid FormId { get; set; }

        [Display(Name="From:")]
        public DateTime From { get; set; }

        [Display(Name = "To:")]
        public DateTime To { get; set; }
    }

剃刀/HTML:

@model ViewFormSubmissionsVM

    @using (Ajax.BeginForm("ViewFormSubmissions", "Form", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onGetSubmissionSuccess", OnFailure = "onGetSubmissionError" }, new { @class = "form-horizontal" }))
    {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(x => x.FormId)
        <div class="row col-md-12">
            <div class="pull-right">
                <label class="control-label col-md-3">@Html.DisplayNameFor(x => x.From)</label>
                @Html.TextBoxFor(x => x.From, "{0:MM/dd/yyyy}", new { @class = "form-control col-md-3", @data_picker = "date-picker" })
                <label class="col-md-3">@Html.DisplayNameFor(x => x.To)</label>
                @Html.TextBoxFor(x => x.To, "{0:MM/dd/yyyy}", new { @class = "form-control col-md-3", @data_picker = "date-picker" })
                <input type="submit" class="btn btn-primary" value="Search" />
            </div>
        </div>
    }

JQuery 日期选择器:

$(document).ready(function () {
    $('*[data-picker="date-picker"]').datepicker();
});

此问题是在提交表单时,“From”和“To”Datetime 属性接收到默认日期值而不是选中。

我错过了什么重要的东西吗?我已经以不同的形式使用过这些代码,但以前从未体验过。

谁能帮我摆脱这个问题。

非常感谢。

【问题讨论】:

  • 模型日期是空白还是您为它们设置了值?
  • 有值,返回 View(new ViewFormSubmissionsVM { FormId = id, From = DateTime.Now.AddMonths(-1), To = DateTime.Now });
  • 服务器的文化是什么?它是不变的还是接受DateTime 格式的MM/dd/yyyy

标签: asp.net-mvc jquery-ui datetime datepicker ajax.beginform


【解决方案1】:

首先,我认为你应该调用这个重载:

using (Ajax.BeginForm("ViewFormSubmissions", "Form", null, new AjaxOptions{ 
    HttpMethod = "POST", 
    OnSuccess = "onGetSubmissionSuccess", 
    OnFailure = "onGetSubmissionError" 
    }, 
    new {@class = "form-horizontal" }))

第三个参数为 null。

其次,检查您的日期时间格式。您可以在此处找到更多信息:MVC DateTime binding with incorrect date formatASP.NET MVC datetime culture issue when passing value back to controllerhttp://weblogs.asp.net/melvynharbour/mvc-modelbinder-and-localization

【讨论】:

  • 对不起,这没有运气。:(
  • @user3534886 尝试将ToFrom的类型从DateTime更改为string,看看传递给控制器​​的是什么。
  • 是的。使用“字符串”类型而不是“日期时间”工作正常。但这背后的原因是什么?
  • @user3534886 您在To / From 字段中获得的日期时间格式是什么?服务器期望的 DateTime 格式是什么?您可以查看:stackoverflow.com/questions/7889038/…weblogs.asp.net/melvynharbour/mvc-modelbinder-and-localization
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多