Shuaib
Shuaib

Reputation: 753

cannot use jquery datepicker with Razor view

I am working on a ASP.NET MVC 4 app. In one of my forms (using Razor view engine) I want to use a jquery datepicker with a date field. But my datepicker code does not work.

Views/Shared/_Layout.cshtml

<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
     <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>

Views/MyController/Create.cshtml

@model wppf_test_1.Models.allocation_percentage

@{
    ViewBag.Title = "Create";
}

<script type="text/javascript">

$(document).ready(function () {

    alert("h");
    $("#date").datepicker();

});

</script>

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

<fieldset>
    <div class="editor-label">
        @Html.LabelFor(model => model.date)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.date)
        @Html.ValidationMessageFor(model => model.date)
    </div>

I am not posting the entire code of the view since it is very large. The alert message in the jquery code works. But the datepicker code does not. I used firebug and verified that the id of the date field is indeed "date". Yet I do not know what is the problem.

Upvotes: 0

Views: 1717

Answers (2)

kikiwisaka
kikiwisaka

Reputation: 41

I have case same like Shuaib and I try your suggest above and I can the date picker on my project (create.cshtml).

<input type="text" name="CreatedDate" id="date" />

But, I have many more input element again in my project (create.cshtml). I try to use same id (id="date") like belowing.

<input type="text" name="UpdatedDate" id="date" /> 

And I running the apps, the date picker on my second input element (name="UpdatedDate) cannot work. I got warning message is Another object on this page is already uses ID 'date'.

What's this method (call id datepicker) only can use one input element (not more) on the page?

Thanks for advice, cheers

Upvotes: 0

TudyTech
TudyTech

Reputation: 84

I would suggest using an input element like so:

<div class="editor-field">
    <input type="text" name="date" id="date" /> 
    @Html.ValidationMessageFor(model => model.date)
</div>

as the editor for your date. Setting the name to date will properly link the value to your date field on form submit. I've had this problem before and this is how I solved it, though I cannot say for certain why it worked.

Upvotes: 2

Related Questions