将选定日期从jqueryui datepicker绑定到model

时间:2016-09-22 01:22:49

标签: asp.net-mvc entity-framework jquery-ui datepicker

我试图将所选日期从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>

1 个答案:

答案 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,并使用表单集合参数和模型绑定方案检查提交的工作方式。

需要关注的其他事项:

  1. 确保EditorFor标记在<form>内,或尝试@using (Html.BeginForm("Create", "Controller", FormMethod.Post))并将EditorFor放入其中。

  2. 确保datepicker提供的日期格式的格式正确System.DateTime可识别,不要依赖JS格式(如果有的话,请避免使用toLocaleDateString)。如果要使用特定的日期格式,请使用momentjs库。

  3. 确保正确加载jQuery,在页面加载后检查浏览器控制台是否有jQuery的存在(查看是否存在TypeError: jQuery is not defined消息)。

  4. 尝试将普通DateTime设置为可空DateTimepublic DateTime? DateOfBirth { get; set; }并插入一些代码以检查空值。

  5. 与进一步参考相似的问题:

    MVC 4 DatePicker's selected value not getting set to model

    Bind Datetime Model value to datepicker and pass them to controller method