views:

81

answers:

3

I'm trying to use AJAX via jquery with ASP.NET MVC, but I'm not able to hit my controller action and I think it might be because my url is not specified correctly.

The problem is, I'm not sure what is should be!

Say I have a controller named "Home", and an action named "AjaxAction", would the jquery look like this?

$.get("Home/AjaxAction");

This doesn't seem to be working for me, so I'm wondering if there's a more correct way to do this using Html helpers or something from ASP.NET MVC.

For instance, has anyone tried doing something like this?

<a href="#" 
    onclick="doSomeFunction('<%= Url.Action("AjaxAction", "Home") %>')">
    Click Me
</a>
<script>
    function doSomeFunction(url)
    {
        $.get(url);
    }
</script>

Would that work or am I barking up the wrong tree? I've tried it myself but it's not working, but I'm not sure if it's because I'm doing something wrong or if it's because the entire approach is incorrect.

+1  A: 

Don't know if you cut/pasted wrong, but you are missing a parenthesis. Also, add single quotes around the URL.

onclick="doSomeFunction('<%= Url.Action("AjaxAction", "Home") %>')"

Give that shot.

The only other difference I have in my code is 'return' in front of doSomeFunction(), but I'm a javascript idiot so probably just cut/pasted that from someplace else, no idea if you need it.

eyston
Thanks @eyston, I'll edit my question. I didn't copy and paste, so that was just me fat fingering, but I'll check on those things just to be sure.
Joseph
I was missing the closing parenthesis =P The weird thing is I wasn't getting any errors so it was hard to catch it. Gotta love javascript debugging =P
Joseph
A: 

It should work. Mine looks a bit different but similar in concept:

<script type="text/javascript">
function myFunct() {
    var url = '<%= Url.Action ("AjaxAction", "Home") %>';
    $.get(url, function(data) {
         // do stuff here
    });
}
</script>

And my HTML:

<a href="javascript:myFunct()">click here</a>
Johannes Setiabudi
I'm going to try it again. I'm not sure what I'm doing wrong but maybe if I start over again I'll see what I missed.
Joseph
A: 

When Web is the default page Your code ($.post("Home/AjaxAction");) is correct

Otherwise you have to specify(($.post("AjaxAction");) actionmethod Only

-Muthukumar