[英]My date doesn't seem to be posting back in the form to the controller
My model has a object which has a date property... 我的模型有一个具有日期属性的对象......
[Required(ErrorMessage="{0} is required")]
[Display(Name="Donation date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DonationDate { get; set; }
The view has an editor for it.... 该视图有一个编辑器....
<div class="editor-label">
@Html.LabelFor(model => model.Donation.DonationDate)
</div>
<div class="editor-field">
@Html.TextBox("txtDate", Model.Donation.DonationDate.ToString("dd/MM/yyyy"), new { @class = "date" })
@Html.ValidationMessageFor(model => model.Donation.DonationDate)
</div>
The controller just receives back the model... but when I do this in the controller and give it to another view... 控制器只接收模型......但是当我在控制器中执行此操作并将其提供给另一个视图时......
ViewBag.Date = model.Donation.DonationDate;
Every time I just get back 1/1/0001 12:00:00 AM no matter what the date was set to. 每次我回到1/1/0001 12:00:00 AM,无论日期是什么时间。 Any thoughts? 有什么想法吗? Thanks! 谢谢!
Forgot to mention... I'm also using JQuery datepicker on the editor field: 忘了提...我也在编辑器字段上使用JQuery datepicker:
$('.date').attr("placeholder", "dd/mm/yy").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true
});
You can use TextBoxFor so that the view engine knows how to label the form field appropriately (so that the model binder will recognize it on postback): 您可以使用TextBoxFor,以便视图引擎知道如何正确标记表单字段(以便模型绑定器在回发时识别它):
@Html.TextBoxFor(model => model.Donation.DonationDate, new { @class = "date" })
Alternatively, you could name the textbox correctly manually. 或者,您可以手动正确命名文本框。 I'm not sure exactly what that would look like ... 我不确定那会是什么样子......
Update 更新
Ok, I as curious so I checked. 好吧,我很好奇,所以我查了一下。 The naming convention for nested fields uses the dot notation. 嵌套字段的命名约定使用点表示法。 So you should be able to write this: 所以你应该写这个:
@Html.TextBox("Donation.DonationDate", Model.Donation.DonationDate.ToString("dd/MM/yyyy"), new { @class = "date" })
Update #2 更新#2
To format the correctly, apply an attribute to the DonationDate property in your model: 要正确格式化,请将属性应用于模型中的DonationDate属性:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
For this to work, you also have to use @Html.EditorFor instead of TextBoxFor. 为此,您还必须使用@ Html.EditorFor而不是TextBoxFor。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.