我试图将所选日期从jQueryUI datepicker绑定到要在控制器中使用的模型,但它返回null。我可以在使用formcollection时检索所选的值
ViewModel
public class EmpViewModel
{
public int EmpId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
查看
<div class="col-md-10">
@Html.EditorFor(model => model.DateOfBirth,
new { htmlAttributes = new { @class = "form-control datefield" } })
</div>
控制器
public ActionResult Create(EmpViewModel emp)
{
}
尝试了下面文章中的方法,但无法使其正常工作 http://www.asp.net/mvc/overview/older-versions/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc-part-4
脚本
<script>
$(function () {
$(".datefield").datepicker();
})
</script>
答案 0 :(得分:0)
将datepicker绑定到viewmodel有多种解决方案,但这两种解决方案很常见:
首先,尝试在EditorFor
上声明一个id属性并将jQuery datepicker绑定到它。
@Html.EditorFor(model => model.DateOfBirth,
new { htmlAttributes = new { @id = "DateOfBirth", @class = "form-control datefield" } })
<script>
$(function () {
$("#DateOfBirth").datepicker();
});
</script>
其次,如果您的模型使用表单提交传递给控制器,请在控制器方法上尝试HttpPost
属性,并在必要时使用ModelState.IsValid
。
[HttpPost]
public ActionResult Create(EmpViewModel emp)
{
if (ModelState.IsValid)
{
// do something
}
}
如果这些解决方案仍然无效,请将EditorFor
更改为TextBoxFor
,并使用表单集合参数和模型绑定方案检查提交的工作方式。
需要关注的其他事项:
确保EditorFor
标记在<form>
内,或尝试@using (Html.BeginForm("Create", "Controller", FormMethod.Post))
并将EditorFor
放入其中。
确保datepicker提供的日期格式的格式正确System.DateTime
可识别,不要依赖JS格式(如果有的话,请避免使用toLocaleDateString)。如果要使用特定的日期格式,请使用momentjs库。
确保正确加载jQuery,在页面加载后检查浏览器控制台是否有jQuery的存在(查看是否存在TypeError: jQuery is not defined
消息)。
尝试将普通DateTime
设置为可空DateTime
:public DateTime? DateOfBirth { get; set; }
并插入一些代码以检查空值。
与进一步参考相似的问题:
MVC 4 DatePicker's selected value not getting set to model
Bind Datetime Model value to datepicker and pass them to controller method