MVC4 _Layout.cshtml Bundles For Scripts

Shane LeBlanc picture Shane LeBlanc · May 22, 2012 · Viewed 7.1k times · Source

In the head section of my _Layout.cshtml page I have this line of code...

<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>

I check the scripts directory and jquery-ui is in there just fine. I'm fairly new to MVC and especially MVC4. I've worked with 3 and I don't believe there was anything to do with Bundles from what I recall, or at least used. From what I get, this bundles up all the scripts into a tightly typed up text format taking out spaces and whatnot. So what I'm assuming is that jquery-ui is going to be added to each page since it's a shared page like a Master Page in Web Forms.

Now in my Index.cshtml file that uses this shared layout page I have at the top.

$(function () {
    $('#DateOfBirth').datepicker();
});

I've added a partial view with this code as well in my Index.cshtml file.

@Html.Partial("_SignUp", Model)

The partial view contains the field I'm trying to add it to. Unfortunately, it isn't adding the datepicker to the input field of type=text, and yes, the id="#DateOfBirth" for this field. What's the deal?

Edit: I do get this error - "Uncaught TypeError: Object [object Object] has no method 'datepicker'

Answer

Darin Dimitrov picture Darin Dimitrov · May 22, 2012

I can't see anything wrong with your code and I am unable to reproduce the problem (ASP.NET MVC 4 Beta). The following works fine for me:

  1. Create a new ASP.NET MVC 4 project using the Internet Template
  2. Add a view model:

    public class MyViewModel
    {
        public DateTime DateOfBirth { get; set; }
    }
    
  3. HomeController:

    public class HomeController : Controller
    {
         public ActionResult Index()
         {
            return View(new MyViewModel
            {
                DateOfBirth = DateTime.Now
            });
        }
    }
    
  4. Index.cshtml:

    @model MyViewModel
    
    <script type="text/javascript">
    $(function () {
        $('#DateOfBirth').datepicker();
    });
    </script>
    
    @Html.Partial("_SignUp", Model)
    
  5. _SignUp.cshtml

    @model MyViewModel
    @Html.EditorFor(x => x.DateOfBirth)
    
  6. Result:

enter image description here

So I guess now the question becomes, what did you do differently?