简体   繁体   中英

jquery .click function not working in c# mvc3 w/ Razor

For far too long I've been stumbling around trying to make a simple .click jquery method work in my c# site. I just want it to call to a function in my controller, but I can't seem to get any button click to register. The calls in it are very similar to a .change() function for another control that works just fine.

JQuery method in question:

$('#addUserButton').click(function () {
            var e = document.getElementById('searchDDL');
            var itemText = e.options[e.selectedIndex].text;
            var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText);
        });

HTML of button that is intended to trigger the above function:

<button id="addUserButton" type="button" value="addUser">&gt;</button>

Some things I've researched and tried already:

  • Changing from a .click() method to a .live("click", etc) method made no difference.
  • I saw that setting the button type="submit" would be a problem, so I changed it to "button."
  • I made sure to include it in document.ready() - I was already doing this before researching other problems.

I have created a jsfiddle for the problem here . I had to remove a lot of sensitive information so the page is not fully fleshed out. It is for an internal application and only has to work with IE.

EDIT: Below I am adding the function I am trying to call in my controller; other posters have verified that the jquery is working as expected, so I'm inclined to believe it is something to do with my c#.

public ActionResult AddUser(string User)
    {
        //numUsers = App.NumberUsers + 1;
        selectedUsers.Add(User);
        return RedirectToAction("ApplicationForm");
    }

Did you try debugging your function or even putting alerts in it to flesh out whats happening.

$('#addUserButton').click(function () {
alert("FUNCTION IS GETTING CALLED ON CLICK EVENT");
            var e = document.getElementById('searchDDL');
alert(e);
            var itemText = e.options[e.selectedIndex].text;
alert(itemText);
            var url = encodeURI('@Url.Action("AddUser")' + "?User=" + itemText);
alert(url);
        });

Doesn't look like your function makes an AJAX request after getting the URL.

像这样多余的结束>括号不是一件愚蠢的事情吗?

<button id="addUserButton" type="button" value="addUser">></button>

From your JSFiddle , it seems you're not including the jQuery .

Which is at the top-left corner of JSFiddle.

I've updated fiddle working fine. Remember you're including jQuery , so try to make use of its feature and leave Javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM