dirk kuyt
dirk kuyt

Reputation: 11

jsonresult does not come back?

trying to display a success message from the controller?

  [HttpPost]
    public JsonResult SuccesMsg()
    {
        return Json(new { Success = true });
    }

jquery:

        $("#but").click(function () {
            $.ajax({
                url: "/Home/SuccesMsg",
                type: 'POST',
                data: "",
                success: function (result) {
                    if (resultJson['Success'] == true) {
                        alert('success');
                    }

                    else
                    { alert('no'); }
                },
                error: function (err) { alert('error') }
            });
        });

Upvotes: 1

Views: 469

Answers (4)

Bhanu Krishnan
Bhanu Krishnan

Reputation: 3726

i think u need to specify as below in your jquery.ajax :

dataType: 'json'

 $("#but").click(function () {
            $.ajax({
                url: "/Home/SuccesMsg",
                dataType: 'json', // change code
                type: 'POST',
                data: "",
                success: function (result) {
                    if (result['Success'] == true) {
                        alert('success');
                    }

                    else
                    { alert('no'); }
                },
                error: function (err) { alert('error') }
            });
        });

Upvotes: 2

LeftyX
LeftyX

Reputation: 35587

In MVC2 use JsonRequestBehavior.DenyGet has said here

  [HttpPost]
    public JsonResult SuccesMsg()
    {
        return Json(new { Success = true }, JsonRequestBehavior.DenyGet);
    }

Upvotes: 0

lmf232s
lmf232s

Reputation: 36

Just tested this and it should work. You want

if (result.Success) {....}

instead of

if (resultJson['Success'] == true) {..}

So entire example

[HttpPost]
    public JsonResult SuccesMsg()
    {
        return Json(
            new
            {
                Success = true
            }
        );
    } 

$.ajax({
    url: '/Home/SuccesMsg',
    type: 'POST',
    success: function (result) {
        if (result.Success) {
            alert('success');
        } else {
            alert('no');
        }
    },
    error: function () {
        alert('error');
    }
});

You should also specify the dataType but not required: http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests

Upvotes: 1

heikkim
heikkim

Reputation: 2975

Add dataType: "json" to your $.ajax call or use the shorthand: $.getJSON.

Also check that your controller handles the response returns in state http 200 (OK).

For debugging, you could add complete: function(){alert('complete');} to see if the request completes or not. Good debugging tools (add-ons) for Firefox are Live http headers and Firebug.

Upvotes: 3

Related Questions