1

モデルに1つのDateTimeプロパティを含めることは可能ですが、ビュー/フォームの2つの入力として使用できますか?たとえば、日付部分はjqueryui datepickerを使用し、時間部分ピッカーはマスクされた入力またはその他の気の利いたjqueryプラグインになります。時々、時間の選択(時間と分)に2つのドロップダウを使用する必要があります。

私の目標は、モデルに1つのDateTimeプロパティを含めることです(日付と時刻の部分的な文字列はありません)。これは可能ですか?MVC4を使用します。

4

3 に答える 3

3

これは、ViewModelに1つのDateTimeプロパティしかないときに、日付を3つのフィールドに分割するために使用する手法です。正確にはあなたが求めているものではありませんが、あなたはあなたが望むものを達成するために同様の方法を使うことができるはずです。

エディターテンプレート /views/shares/editortempaltes/datetime.cshtml

@model Nullable<System.DateTime>         
@Html.TextBox("Day", Model.HasValue ? Model.Value.Day.ToString() : "", new { Type = "Number", @class="date-day" })
@Html.ValidationMessage("Day")
@Html.DropDownList("Month", months, new { @class="date-month" })
@Html.ValidationMessage("Month")
@Html.TextBox("Year", Model.HasValue ? Model.Value.Year.ToString() : "", new { Type = "Number", @class="date-year" })
@Html.ValidationMessage("Year")

カスタムModelBinder

public object GetValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
    int day, month, year;

    if (TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Day", out day) && TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Month", out month) && TryGetValue(controllerContext, bindingContext, propertyDescriptor.Name + ".Year", out year))
    {
        try
        {
            return new DateTime(year, month, day);
        }
        catch (ArgumentOutOfRangeException)
        {
            var fullPropertyName = bindingContext.ModelName + "." + propertyDescriptor.Name;               
            bindingContext.ModelState[fullPropertyName] = new ModelState();                         
            bindingContext.ModelState[fullPropertyName].Errors.Add("Invalid date");
        }
    }
    return null;
}


private bool TryGetValue(ControllerContext controllerContext, ModelBindingContext bindingContext, string propertyName, out int value)
{
    var fullPropertyName = bindingContext.ModelName + "." + propertyName;
    string stringValue = controllerContext.HttpContext.Request[fullPropertyName];
bindingContext.ModelState.Add(fullPropertyName, new ModelState() { Value = new ValueProviderResult(stringValue, stringValue, null) });
    return int.TryParse(stringValue, out value);
}

使用法 ViewModelにDateTimeプロパティを追加してから、

@Html.EditorFor(m => m.DateTimeProperty)
于 2012-10-26T07:40:30.703 に答える
2

提案されたソリューションの代わりに、DateTimeプロパティにマップされた非表示フィールドを使用し、フォームの一部のコントロールが日付の一部を変更したときに、Javascriptを使用してクライアント側でそれに応じて変更できます。

于 2012-10-26T07:25:35.600 に答える
0

はい、できます。モデルをビューに渡し、値をフィールドに渡そうとしている場合に通常行うようにDateTimeを使用します。

データを取得するには、2つのDateTime(1つは秒用、もう1つは時間用)を返し、コントローラーで2つの日付を組み合わせることができます。

より具体的なヘルプが必要な場合は、コードのどこで問題が発生しているのかを示して、実装を支援できるようにしてください

于 2012-10-25T20:50:59.220 に答える