【问题标题】:Bind selected date from jqueryui datepicker to model将 jqueryui datepicker 中的选定日期绑定到模型
【发布时间】:2016-09-22 01:22:48
【问题描述】:

我正在尝试将 jQueryUI 日期选择器中的选定日期绑定到要在控制器中使用的模型,但它返回 null。使用 formcollection 时,我可以检索选定的值

视图模型

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>

【问题讨论】:

  • 那个教程已经有五年了,你的 MVC 版本是多少?请粘贴您的EmpViewModel
  • @naveen - MVC 5,包括视图模型
  • 显示你为 datepicker 连接的 jquery 代码。
  • @Jecoms - 包含日期选择器
  • 浏览器控制台有什么错误吗?

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


【解决方案1】:

将 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 包含在&lt;form&gt; 标记内,或尝试@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 设置为可空 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

【讨论】:

  • 通过添加 id 实现第一个点是绑定不正确的日期 01/01/0001 12:00:00 AM,我如何“确保 datepicker 提供的日期格式是系统可识别的正确格式.DateTime" 这样做?
  • 尝试在客户端使用console.log($("#DateOfBirth").val())或类似方式获取EditorFor给出的日期时间输出值。您可以检查控制台输出在传递给模型时是否适合正确的DateTime 格式。
  • Stephen 的解决方案在 stackoverflow.com/questions/28042366/… 中对我有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
相关资源
最近更新 更多