MVC 3 - 将 Html.TextBox 更改为 Html.TextBoxFor
我使用 html.textbox 作为我的 2 个日期时间字段,因为我需要以特定格式格式化它们,但我不知道如何通过 html.textboxfor 来做到这一点。 但是,我意识到我需要在模型类中使用 textboxfor 进行验证才能工作:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
知道如何将下面的 Html.Textbox 更改为具有相同设置的 Html.TextBoxFor 吗?
@Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
@Html.ValidationMessageFor(model => model.ExpiryDate)
感谢任何帮助...谢谢...
I am using html.textbox for 2 of my datetime field because I need to format them in a specific format but i don't know how to do it by html.textboxfor.
However, I realise i need to have the textboxfor for the validation in my model class to work:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
Any idea how can I change my Html.Textbox below into Html.TextBoxFor with the same setting??
@Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
@Html.ValidationMessageFor(model => model.ExpiryDate)
Appreciate any help... Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上并不需要使用
TextBoxFor()
来进行验证。如果您的 TextBox 与模型中的字段具有相同的 id,则模型绑定器将选择它。如果您正在谈论获得不显眼的验证功能,您始终可以手动将 data-* 属性添加到您的文本框。然而,在这种情况下,听起来您真正想要的是使用
EditorFor()
的自定义编辑器。这需要更多的工作,但它允许您通过为用户提供诸如日期/时间选择器控件之类的东西来实际强制执行日期/时间格式。基本思想是:Nullable
类型的模型,并将其放入Shared/EditorTemplates
视图文件夹中。[DataType(DataType.DateTime)]
属性装饰模型上的属性Html.EditorFor(model => model.WhateverProperty)
幸运的是,日期/时间选择器可能是最流行的自定义 MVC3 编辑器,因此有很多示例可供选择; 这个问题中的代码工作正常,只需确保注意答案中的建议并将部分视图中的这一行替换
为:
You don't really need to use
TextBoxFor()
for validation to work. If your TextBox has the same id as a field in the model, the model binder will pick it up. If you're talking about to get the unobtrusive validation features, you can always manually add the data-* attributes to your TextBox.However, in this case it sounds like what you really want is a custom editor, using
EditorFor()
. It's a bit more work, but it will allow you to actually enforce the date/time formatting by giving the user something like a date/time picker control. The basic idea is:Nullable<DateTime>
, and put it into theShared/EditorTemplates
view folder.[DataType(DataType.DateTime)]
attributeHtml.EditorFor(model => model.WhateverProperty)
Fortunately, date/time pickers are probably the most popular custom MVC3 editor, so there are plenty of examples to pick from; the code from this question works fine, just make sure to note the suggestion in the answer and replace this line in the partial view:
with this: