亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在asp.net mvc 4中格式化datetime

在asp.net mvc 4中格式化datetime

楊魅力 2019-11-27 10:12:45
如何在asp.net mvc 4中強制使用datetime格式?在顯示模式下,它顯示為我想要的,但在編輯模型中,它沒有顯示。我正在使用displayfor和editorfor,并使用dataformatstring =“ {0:dd / MM / yyyy}”來applyformatineditmode = true進行了嘗試:我的文化和uiculture在web.config(兩者)中都實現了全球化。在application_start()中修改文化和uiculture用于日期時間的自定義modelbinder我不知道如何強制執行,我需要輸入日期作為dd / MM / yyyy而不是默認值。更多信息:我的視圖模型是這樣的    [DisplayName("date of birth")]    [DataType(DataType.Date)]    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]    public DateTime? Birth { get; set; }在我看來,@Html.DisplayFor(m=>m.Birth)但是這可以按預期工作(我看到格式)并輸入我使用的日期,@Html.EditorFor(m=>m.Birth)但是如果我嘗試輸入類似13/12/2000的內容,則會失敗,并顯示錯誤的日期(12 / 13/2000和2000/12/13正常工作,但我需要dd / MM / yyyy)。自定義modelbinder在application_start()b / c中調用,我不知道在其他地方。使用<globalization/>我嘗試過的culture="ro-RO", uiCulture="ro"和其他會給我dd / MM / yyyy的文化。我也嘗試在application_start()中基于每個線程設置它(這里有很多示例,關于如何執行此操作)對于所有將要閱讀的問題:只要我沒有客戶端驗證,Darin Dimitrov的答案似乎就會起作用。另一種方法是使用定制驗證,包括客戶端驗證。我很高興在重新創建整個應用程序之前就發現了這一點。
查看完整描述

3 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

啊,現在很清楚。您似乎在綁定值時遇到問題。不能在視圖上顯示它。確實,這是默認模型綁定程序的錯誤。您可以編寫并使用一種定制[DisplayFormat]模型,該模型將考慮模型上的屬性。我已經在這里說明了這樣的自定義模型活頁夾:https : //stackoverflow.com/a/7836093/29407


顯然,一些問題仍然存在。這是我的完整設置,可以在ASP.NET MVC 3和4 RC上正常運行。


模型:


public class MyViewModel

{

    [DisplayName("date of birth")]

    [DataType(DataType.Date)]

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]

    public DateTime? Birth { get; set; }

}

控制器:


public class HomeController : Controller

{

    public ActionResult Index()

    {

        return View(new MyViewModel

        {

            Birth = DateTime.Now

        });

    }


    [HttpPost]

    public ActionResult Index(MyViewModel model)

    {

        return View(model);

    }

}

視圖:


@model MyViewModel


@using (Html.BeginForm())

{

    @Html.LabelFor(x => x.Birth)

    @Html.EditorFor(x => x.Birth)

    @Html.ValidationMessageFor(x => x.Birth)

    <button type="submit">OK</button>

}

在以下位置注冊自定義模型活頁夾Application_Start:


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

以及自定義模型活頁夾本身:


public class MyDateTimeModelBinder : DefaultModelBinder

{

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

    {

        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;

        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);


        if (!string.IsNullOrEmpty(displayFormat) && value != null)

        {

            DateTime date;

            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);

            // use the format specified in the DisplayFormat attribute to parse the date

            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))

            {

                return date;

            }

            else

            {

                bindingContext.ModelState.AddModelError(

                    bindingContext.ModelName,

                    string.Format("{0} is an invalid date format", value.AttemptedValue)

                );

            }

        }


        return base.BindModel(controllerContext, bindingContext);

    }

}

現在,無論您在web.config(<globalization>元素)中設置了哪種區域性還是當前的線程區域性,自定義模型綁定程序DisplayFormat在解析可為空的日期時都將使用屬性的日期格式。


查看完整回答
反對 回復 2019-11-27
  • 3 回答
  • 0 關注
  • 752 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號