JQuery UI datepicker in Asp.Net MVC

后端 未结 4 723
南笙
南笙 2020-12-30 05:49

I have tried to use some of the widgets in JQuery UI on an Asp.Net MVC site without luck.

For example the basic datepicker from jQuery UI -

相关标签:
4条回答
  • 2020-12-30 06:00

    Where in the page are you loading scripts & where are you calling the datepicker initialization?

    Here is a sample of using jQuery shorthand document ready & css selectors to initialize datePickers more easily.

    Here is the razor code for a sample input box (notice the "datefield" css class)

    <div class="form-group">
        @Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.DateOfBirth, new { @class = "form-control datefield" })
        </div>
    </div>
    

    Here is the javascript needed to initialize any datepicker by css selector

    $(function () {
        $(".datefield").datepicker();
    });
    

    I've put together a tutorial detailing the specifics & a sample ASP.NET MVC5 solution on github

    http://prestoasp.net/using-the-jquery-datepicker-with-asp-net-mvc/ https://github.com/fredo007/i6technology/tree/master/InsuranceSales

    0 讨论(0)
  • 2020-12-30 06:03

    Make sure your initializer is called after the DOM is loaded:

    $(document).ready(function() {
        $("#basics").datepicker();
    });
    

    jQuery ready event:

    By using this method, your bound function will be called the instant the DOM is ready to be read and manipulated, which is when 99.99% of all JavaScript code needs to run.

    0 讨论(0)
  • 2020-12-30 06:12

    It looks like you are executing the JavaScript inline as the page loads. In which case the #basics selector won't be able to locate the input with id="basics" as it hasn't yet been parsed and rendered in to the document body.

    Your solution may be as simple as as moving the script element in your code to a position after the input element.

    Better still, subscribe to a document ready or document loaded event and execute the jQuery code in the handler of that event.

    $(document).ready(function() {
        $("#basics").datepicker();
    });
    

    There's a number of advantages to that. You can be sure that the entire DOM is ready for use, and there is no dependency on the order of the source code meaning you could move the JavaScript to an external file in the future to take advantage of various caching mechanisms on the client-side.

    0 讨论(0)
  • 2020-12-30 06:14

    I've got a write-up of this with MVC 3 here: http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx

    0 讨论(0)
提交回复
热议问题