lzc
lzc

Reputation: 1705

MVC4 JQuery Datepicker to capture date from input box

Has anybody got experience using jquery ui's datepicker with Razor @Html.TextBoxFor(...)

I trying to allow the user to select date using Razor mark up to generate a textbox, when clicked will display Datepicker from jquery UI. I'm not sure if by using:

@using (Html.BeginForm("New","Order"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
    @Html.LabelFor(m => m.OrderInfo.installdate)
    @Html.TextBoxFor(m => m.OrderInfo.installdate, new {@id="dp"})
    </fieldset>
}

<script type="text/javascript">
 $(document).ready(function () {

        $("#dp").datepicker();
    });
</script>

@Scripts.Render("~/bundles/jquery") 
@Scripts.Render("~/bundles/jqueryui") 

Ran in this order, and no matter rearrange, unable to display the datepicker.

Can this even be done this way?

Upvotes: 0

Views: 178

Answers (1)

Jasen
Jasen

Reputation: 14250

Make sure you've bundled the resources

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js");
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include("~/Scripts/jquery-ui-{version}.js");
bundles.Add(new StyleBundle("~/bundles/themes/base").Include(
    "~/content/themes/base/jquery.ui.core.css",
    "~/Content/themes/base/jquery.ui.datepicker.css",
    ...
);

Include them in the proper order

Layout.cshtml

<html>
<head>
    @Styles.Render("~/bundles/themes/base")
</head>
<body>
    @RenderBody()
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @RenderSection("page_scripts", required: false)
</body>

Now the View... Since the scripts were included on the Layout the view doesn't need it.

@Html.TextBoxFor(m => m.installdate, new { @id="dp" })

@section page_scripts {
    <script>
        $(document).ready(function () {
            $("#dp").datepicker({ ... });
        });
    </script>
}

If you don't have it on the Layout or don't use one then

@Html.TextBoxFor(m => m.installdate, new { @id="dp" })

@Styles.Render("~/bundles/themes/base")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
<script>
    $(document).ready(function () {
        $("#dp").datepicker({ ... });
    });
</script>

Upvotes: 1

Related Questions