1

How can I call the same action using ajax from different pages?

type: 'POST',
  url: 'Notification/GetRecentNotifications/'

I'm currently using the code above to call my action. It works for my application's home page, but when I change to other page, this doesn't work. Can anybody give me a solution? Thanks before.

1
  • Please, put the code sample for analysis. Commented Dec 1, 2011 at 15:08

2 Answers 2

3

Heres what I usually do to point to which controller & action to call within an ajax jquery call...

 $.ajax({
            type: "POST",
            url: '@(Url.Action("Action", "Controller"))',
            success: function (data) {

            }
        });

Use Url.Action() to build links

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

1 Comment

is it possible for me to separate the javascript code when I call an asp function like that inside the script?
0

Put the code in a ajax.js file in your scripts directory then reference it in the pages where you need to use the methods in that file. Then, put any server side logic for your ajax calls in an AjaxController For example:

ajax.js

function foo() { 
    var model = { };

    $.ajax({
        url: '@Url.Action("Foo", "Ajax")',
        type: "POST",
        data: JSON.stringify(model),
        success: function(data) { 
            alert(data);
        },
        error: function(data) {
            alert(data);
        }
    });    
}

AjaxController.cs

public class AjaxController : Controller
{
    [HttpPost]
    public JsonResult Foo(FooModel model)
    {
        string message = _ajaxService.Foo(model);

        return Json(message);
    }
}

In the example above _ajaxService is a service layer object that contains the logic to handle your ajax requests. Below is how to use the function in your view:

SomeView.cshtml

<script type="text/javascript" language="javascript" src="@Url.Content("~/Content/Scripts/ajax.js")"></script>
<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        $('#button').click(foo);
    });
</script>

If there is additional logic to pass data to the ajax method that is reused, you should probably put it in a partial view and reference that from every view that needs it.

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.