Mike Upjohn
Mike Upjohn

Reputation: 1297

$.ajax and C# MVC Controller returns error or nothing

I have an AJAX JS functions which calls a C# MVC HttpPost Controller. This will return an object but for the purposes of debugging I am just trying to return a string.

JS AJAX code:

function UpdateBlogFilters(month, year) {

var url = "/HttpPost/GetBlogPostsPerMonth";

if (month != null && month != "" && year != null && year != "") {
    alert(month + " " + year);
    $.ajax({
        url: url,
        data: { monthValue: month, yearValue: year },
        cache: false,
        type: "POST",
        success: function (data) {
            console.log("Data " + data);
            var markup = "";
        },
        error: function (response) {
            console.log(response.responseText);
            console.log("Error: " + response);
        }
    });
    console.log("1");
}
console.log("2");
}

Controller Code:

[HttpPost]
    public ActionResult GetBlogPostsPerMonth(int monthValue, int yearValue)
    {
        .... the non-debug code
        return Json("test");
    }

This is returning an error, but the responseText and any error information is blank? I have verified that the controller is being called and it is reaching the return statement in the C# without error.

Any help?

Upvotes: 3

Views: 1611

Answers (3)

user2812143
user2812143

Reputation: 13

Why do you have "/HttpPost/" in url? Is that name of a controller that is different from the one you are using to render the view? Can you try without /HttpPost/

  var url = "GetBlogPostsPerMonth";

Upvotes: 0

Glenn Ferrie
Glenn Ferrie

Reputation: 10390

Change your C# code to read something like this:

[HttpPost]
public ActionResult GetBlogPostsPerMonth(int monthValue, int yearValue)
{
    .... the non-debug code
    return Json(new { result = "test" });
}

Ultimately, you want to pass an object into Json(). You can pass an instance of a class, or an anonymous type, or dynamic.

Upvotes: 1

Mike Upjohn
Mike Upjohn

Reputation: 1297

This was the solution. The AJAX call in itself worked fine. All code posted here was correct as per Bhavik.

The issue was that this AJAX request was called onclick of a hyperlink and this hyperlink although having no href set, was refreshing the page and somehow cancelling off the AJAX request. Removing the href to leave

<a onclick="UpdateBlogFilters(5,2014)">

resulted in the object being returned from AJAX successfully.

Upvotes: 0

Related Questions