1

Inside my main view I have ajax action links

e.g.

  @Ajax.ActionLink("Update Hours", "companyhours", "business",
 new { Id = ViewBag.Id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "divCurrentView" })

Inside the controller

 public ActionResult CompanyHours(string Id)
    { ...   return PartialView("UpdateCompanyHours", model);}

the view gets loaded on click

the partial view "UpdateCompanyHours.cshtml" i have

@model CompanyHoursVM
@{Layout = null; }
@using (Ajax.BeginForm("CompanyHours", new AjaxOptions { UpdateTargetId = "presult", HttpMethod = "POST", InsertionMode = InsertionMode.Replace }))
{     
  @Html.ValidationSummary(true)
  @Html.AntiForgeryToken()

  // i have textboxes and a button - everything loads fine
  @Html.CheckBoxFor(model => model.Open247, new { @class = "Time24hrs"})
 }

Here is the issue:

I want to add my js file inside my main view. Add the code to the bottom of the main view page:

@section Scripts
{
    <script src="~/Scripts/myjs.js"></script>
}

or even without the @section Scripts tag

js file very simple. the first alert is executed but onclick it does not

(function () {
$(function () {
    alert("alert1");
    $('.Time24hrs').click(function () {
        alert("alert2");
    });
});
})();

The js is not been recognized. But if I add the js file inside the partial view it works fine

How can I make the js file load in the main view and use the js file inside the partial view?

2 Answers 2

3

When you click on "Update Hours" link ,the ajax code is dynamically injecting new DOM elements to the current dom (markup from the partial view). But your click event was registered with the existing elements (current elements when the page loaded). There is no click event handlers registered for these new dom elements.

Use jQuery on method to bind the click event. With on method, you can register events for current and future elements of the DOM

This should work.

$(function () {

    $(document).on("click",".Time24hrs",function () {
        alert("alert2");
    });

});
Sign up to request clarification or add additional context in comments.

Comments

0

I bet that ajax call to return your partial completing asynchronously after the main page's load function has been called in which case there is no chance to set the event handler the way you are doing as that element has yet to be added to the dom. You need to somehow notify up when your partial is loaded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.