简体   繁体   English

提交可为空的日期时间为null

[英]Submission of a nullable datetime is null

How to save a TimeOfDay? 如何保存TimeOfDay? [duplicate] haven't an answer and this present post it's about a specific problem an not a general question like that post [重复]尚无答案,此当前信息是关于某个特定问题的,而不是该问题的一般性问题

I'm trying save/submit a Date and a TimeOfDay of a specific DateTime (nullable) variable but when it arrives to my controller its value is always null even user insert other values. 我正在尝试保存/提交特定DateTime(可空)变量的Date和TimeOfDay,但是当它到达我的控制器时,即使用户插入其他值,其值也始终为null How can I solve this? 我该如何解决?

My visual objective: 我的视觉目标:

在此处输入图片说明

My view: 我的观点:

<div style="display:inline-block">
            <div class="editor-label">
                Initial date:
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.StartDate.Value.Date, new { type = "date" })
                @Html.ValidationMessageFor(model => model.StartDate)
            </div>
        </div>

        <div style="display:inline-block">
            <div class="editor-label">
                Initial hour:
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.StartDate.Value.TimeOfDay, new { type = "time" })
                @Html.ValidationMessageFor(model => model.StartDate)
            </div>
        </div>

My model: 我的模特:

[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }

My model binding (from this link what is great but don't work to nullable dates and I don't know why) : 我的模型绑定 (从此链接来看,很棒,但是不适用于可为空的日期,我也不知道为什么)

public class DateTimeModelBinder : DefaultModelBinder
{
    private Nullable<T> GetA<T>(ModelBindingContext bindingContext, string key) where T : struct
    {
        if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
        {
            if (string.IsNullOrEmpty(key)) key = bindingContext.ModelName;
            else key = bindingContext.ModelName + "." + key;
        }
        if (string.IsNullOrEmpty(key)) return null;

        ValueProviderResult value;

        value = bindingContext.ValueProvider.GetValue(key);
        bindingContext.ModelState.SetModelValue(key, value);

        if (value == null)
        {
            return null;
        }

        Nullable<T> retVal = null;
        try
        {
            retVal = (Nullable<T>)value.ConvertTo(typeof(T));
        }
        catch (Exception) { }

        return retVal;
    }

    public override object BindModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        if (bindingContext == null) throw new ArgumentNullException("bindingContext");

        // Check for a simple DateTime value with no suffix
        DateTime? dateTimeAttempt = GetA<DateTime>(bindingContext, "");
        if (dateTimeAttempt != null)
        {
            return dateTimeAttempt.Value;
        }

        // Check for separate Date / Time fields
        DateTime? dateAttempt = GetA<DateTime>(bindingContext, "Date");
        DateTime? timeAttempt = GetA<DateTime>(bindingContext, "TimeOfDay");

        //If we got both parts, assemble them!
        if (dateAttempt != null && timeAttempt != null)
        {
            return new DateTime(dateAttempt.Value.Year,
                dateAttempt.Value.Month,
                dateAttempt.Value.Day,
                timeAttempt.Value.Hour,
                timeAttempt.Value.Minute,
                timeAttempt.Value.Second);
        }

        //Only got one half? Return as much as we have!
        return dateAttempt ?? timeAttempt;
    }
}

The binder is looking for two post values called StartDate.Date and StartDate.TimeOfDay ; 活页夹正在寻找两个名为StartDate.DateStartDate.TimeOfDay帖子值; however, the TextBoxFor method will have named these controls StartDate.Value.Date and StartDate.Value.TimeOfDay instead. 但是, TextBoxFor方法将把这些控件命名为StartDate.Value.DateStartDate.Value.TimeOfDay

Try adding code to your binder to check for these names: 尝试将代码添加到活页夹中以检查以下名称:

DateTime? dateAttempt = GetA<DateTime>(bindingContext, "Date");
DateTime? timeAttempt = GetA<DateTime>(bindingContext, "TimeOfDay");

if (dateAttempt == null && timeAttempt == null)
{
    dateAttempt = GetA<DateTime>(bindingContext, "Value.Date");
    timeAttempt = GetA<DateTime>(bindingContext, "Value.TimeOfDay");
}

The problem was the lack of one ? 问题是缺少一个 on the call of my ModelBinder on Global.asax . 我在Global.asax上调用ModelBinder时。 So its code changed to: 因此其代码更改为:

ModelBinders.Binders.Add(typeof(DateTime?), new Models.DateTimeModelBinder());

and the changes Richard Deeming suggests should be done too: 理查德·迪明Richard Deeming)提出的更改也应做:

if (dateAttempt == null && timeAttempt == null)
{
    dateAttempt = GetA<DateTime>(bindingContext, "Value.Date");
    timeAttempt = GetA<DateTime>(bindingContext, "Value.TimeOfDay");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM