Friday, April 15, 2011

ASP.NET MVC jQueryUI datepicker not working when using AJAX.BeginForm

I have an ASP.NET MVC Partial View that contains a Html.TextBox that is configured to use the datepicker from JQueryUI. This is done by ensuring the style is set to .datepicker. This all worked fine. However I have changed my forms to Ajax.BeginForm and included a Ajax.ActionLink that displays it after clicking on the link. Since adding this the datepicker does not display. In fact no JavaScript that previously worked is now even being invoked after a returning a partialview from the controller. Even if i PUT THE JavaScript/JQuery in the partial view itself it still does not use it. I really am confused, can someone please help?

Examples shown below

<div id="claims">
        <div id="divViewClaims">
            <% Html.RenderPartial("ViewClaim", Model.Claims ?? null); %>
        </div>
        <br /><br />
        <div id="claim">
            <% Html.RenderPartial("AddEditClaim", new Claim()); %>          
        </div>
    </div>

Action Link, when clickon calls Controller Action to return PartialView, The JavaScript called on the OnSuccess fires but nothing else, that previously was hooked up by the document.ready function. All my scripts are in seperate files and referenced in master page.

<%= Ajax.ActionLink(string.Format("Add A{0} Claim", Model.Count > 0 ? "nother" : string.Empty), "AddClaim", "Driver", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "claim", OnSuccess="showAddClaim" }, new { @class = "ControlLink" })%>

Controller Action

public ActionResult AddClaim()
{
      return PartialView("AddEditClaim", new Claim());
}

Partial View, which shows the textbox with the style set to datepicker

<% var ajaxOptions = new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divViewClaims", InsertionMode = InsertionMode.Replace, OnSuccess="hideAddClaim" }; %>
        <% using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { @name = "ClaimControl", @id = "ClaimControl" }))
           { %>

    <fieldset>  
        <legend><%= Model.Id==0?"Add":"Edit" %> Claim</legend> 
        <p>
            <label for="Title">Claim Date</label>
            <%= Html.TextBox("Date", Model.Date.ToString().TrimEnd('0', ':', ' ') ?? "", new { @class = "datepicker" })%>  
        </p>

I appreciate any help on this.

From stackoverflow
  • If the element is created after document.ready you should re-match the element to jQuery.

    Check out jQuery Live

  • I know it's bit too late to answer this ;), but what works for me is to use the OnSuccess property from the AjaxOptions. So, your code could be like this:

    using (Ajax.BeginForm("AddEditClaim", "Claim", ajaxOptions, new { @name = "ClaimControl", @id = "ClaimControl", OnSuccess="the_javascript_function_below" })
    

    where the_javascript_function is the name of a function that does this:

    $(".datepicker").datepicker();
    

0 comments:

Post a Comment