【问题标题】:problem in converting dd.MM.yyyy to MM/dd/yyyy in mvc在 mvc 中将 dd.MM.yyyy 转换为 MM/dd/yyyy 的问题
【发布时间】:2011-04-18 06:59:09
【问题描述】:

我在数据库中有日期时间字段,并且我使用 DateTime 属性作为日期。

我在文本框中以“dd.MM.yyyy”格式显示日期

@Html.TextBox("Validity", Model.Validity.ToString("dd.MM.yyyy"))

现在我必须将它保存到数据库中,这意味着我如何将这个值分配给属性,以便我能够在我的控制器中获取数据。

谢谢。

【问题讨论】:

标签: .net asp.net asp.net-mvc asp.net-mvc-3 datetime-format


【解决方案1】:

在您的控制器中,您可以使用您的模型或 FormsCollection 检索此字段。从那里您可以格式化“。”点字符转换为您期望的格式。

如果你把它作为 SQLDBType.DateTime 传递给 SQL,你应该没问题..

【讨论】:

    【解决方案2】:

    由于您没有解释您在使用此代码时遇到了什么问题,这里有一个对我有用的示例,它允许我在 POST 操作中成功检索以 dd.MM.yyyy 格式存储的日期。

    型号:

    public class MyViewModel
    {
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
        public DateTime Validity { get; set; }
    }
    

    控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel
            {
                Validity = DateTime.Now
            });
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    查看:

    @model MyViewModel
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.Validity)
        <input type="submit" value="OK" />
    }
    

    【讨论】:

    • 我在我的应用程序中使用了您的示例。当我选择像 12.12.2011 这样的日期时,它工作正常,但是当我使用像 18.12.2011 这样的日期时,它在属性(日期时间) 01/01/0001 中设置了值,这对我来说是个问题:(
    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多