Fletch
Fletch

Reputation: 367

Why is javascript not working in asp.net mvc view with shared/partial view

I've tried adding the following script to the end of my Index.cshtml view for my Users page but it isn't being called. I've tried wrapping this in $(document).ready(function () { etc but it doesn't seem to make any difference.

<script>
    $("#UserSearch").click(function () {
        $("#usernameSearchString").text("newText");
    });
</script>

Below is the Index.cshtml view:

@model IEnumerable<CCM.Models.User>

    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>

@{
    ViewBag.Title = "Users";
    ViewBag.CurrentSort = "name_desc";
    ViewBag.NameSortParm = "name_desc";
    ViewBag.DateSortParm = "date_desc";
}

<p class="h2">Manage Users</p>
<input type="text" id="usernameSearchString" placeholder = "Find by user name" class="form-input" />
<a id="UserSearch" class="CMsubmit">Search</a>
<br />
<br />
<div id="usersTable" style="overflow-x:auto;">
    @Html.Partial("_User", Model)
</div>
<script>
    $("#UserSearch").click(function () {
        $("#usernameSearchString").text("newText");
    });
</script>

As the page uses a shared view for the navigation the JQuery references have been kept there in the _Layout.cshtml shared view as follows. I found adding the JQuery reference to my Index.cshtml view caused the JQuery functions to fire twice.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - CCM</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
...navigation...
</body>
</html>

A partial view _User.cshtml is also called to populate a table, the partial view contains no JQuery references and doesn't use javascript.

The above script is just an example, the javascript/JQuery is required in the Index.cshtml view so that I can pass a search filter string to a function in the Controller in order to update the partial view with the filtered results.

However, my question is how can I get inline javascript / JQuery to work at all on my Index.cshtml view?

Upvotes: 1

Views: 3489

Answers (1)

Andrei
Andrei

Reputation: 56688

Since UserSearch is the link, I believe the problem is that your script works, but then the click also triggers the default behavior of the link, so you can't notice your custom script working. You can confirm that by placing a debug breakpoint inside your script and see if the page execution stops there after a click.

Thus you need to prevent the default behavior. This is fairly standard with jQuery:

$("#UserSearch").click(function (event) {
    event.preventDefault();
    $("#usernameSearchString").val("newText");
});

Upvotes: 2

Related Questions