DateState对于DateTimeOffset + MVC4无效

时间:2013-07-01 11:48:27

标签: jquery asp.net-mvc-4 razor

我遇到了datetimeoffset的模型状态问题。 看到答案:Modelstate always throws invalid datetime error但这些并没有解决我的问题。

我在模型中有FromDate:

[Required, Display(Name = "From")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTimeOffset FromDate { get; set; }

我在我的观点中展示了它:

<div class="editor-label">
@Html.LabelFor(O => O.FromDate)

- start--输入data-val =“true”id =“FromDate”name =“FromDate”type =“datetime”class =“datetime”data-datetime =“”value =“@ Model.FromDate。 ToString(“r”)“---结束

@Html.ValidationMessageFor(O => O.FromDate)
</div>

将jquery中的datetime值更改为jquery中的本地时间:

if ($(this.element).val() != "") {
            // If we wont specify time on recreate then time sliders will stay unchanged.
            //  we manipulate datepicker value and value of input to display differently.
            //  LLLL--> Thursday, April 18 2013 1:20 PM
            //  L --> 04/18/2013
            //  LT --> 8:30 PM
           this._Input.datepicker("setDate", new Date(moment($(this.element).val()).format("LLLL")));
           this._Input.val(moment($(this.element).val()).format("L LT"));
        }

然而,当我编辑并保存时,我得到“FromDate无效”例外。

“价值'Fri Jun 14 05:30:00 UTC + 0530 2013'对于From无效。”

有人可以建议如何解决?

Model Binder:

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        //var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;

        string s = bindingContext.ValueProvider.GetValue("FromDate").AttemptedValue;
        string value = bindingContext.ValueProvider.GetValue("ThruDate").AttemptedValue;
        DateTimeOffset from;
        DateTimeOffset thru;
        if (s.IndexOf("UTC") != -1)
        {
              from = DateTimeOffset.ParseExact(s, "ddd MMM dd HH:mm:ss \"UTC\"zzz yyyy", CultureInfo.InvariantCulture);
        }
        else
        {
            from = DateTimeOffset.ParseExact(s, "ddd, dd MMM yyyy HH:mm:ss \"GMT\"", CultureInfo.InvariantCulture);

        }

        if (value.IndexOf("UTC") != -1)
            thru = DateTimeOffset.ParseExact(value, "ddd MMM dd HH:mm:ss \"UTC\"zzz yyyy", CultureInfo.InvariantCulture);
        else
            thru = DateTimeOffset.ParseExact(value, "ddd MMM dd yyyy HH:mm:ss \"GMT\"zzz \"(India Standard Time)\"", CultureInfo.InvariantCulture);



        return PrFactory.Create(Convert.ToInt32(bindingContext.ValueProvider.GetValue("PartyRoleTypeId").AttemptedValue),
            Convert.ToInt32(bindingContext.ValueProvider.GetValue("PartyId").AttemptedValue),
            from,
            Convert.ToBoolean(bindingContext.ValueProvider.GetValue("IsSoftDeleted").AttemptedValue),
            new Party(),
            new PartyRoleType(),
           thru);

        //return base.CreateModel(controllerContext, bindingContext, modelType);
    }

0 个答案:

没有答案