Ben Ben - 2 months ago 19
Javascript Question

MVC using JS inside partial view

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?

Answer

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");
    });

});