slandau
slandau

Reputation: 24052

Calling an MVC Action with JQuery AJAX that doesn't return Json (instead another view)

So I have an MVC Action in my controller

public System.Web.Mvc.ActionResult Link(LinkType type)
        {
            switch (type)
            {
                case LinkType.IC:
                    return RedirectToAction("Indication", "IndicationsController");
                    break;
                case LinkType.Pricing:
                    break;
                case LinkType.Sheets:
                    break;
                case LinkType.Analysis:
                    break;
                case LinkType.Admin:
                    break;
                default : 
                    break;
            }

            return View(@"~\Views\Indications\ShowAString.aspx", "", "Page is not available for selection.");
        }

I want to call this action from JQuery passing the integer value of the button that was clicked. So I have this in my button click method:

$('#btnIc').live('click', function () {
        var typeJSON = {};
        typeJSON["type"] = 1;
        $.ajax({
            type: "POST",
            url: "<%= Url.Action("Link", "Home") %> ",
            dataType: "jsonData",
            data: typeJSON,
            success: function(data) {

            }
        });
    });

Will this redirect the page or will it be waiting for me to do something with (data)?

Is this the correct way to do this?

Upvotes: 4

Views: 4904

Answers (3)

Dan Atkinson
Dan Atkinson

Reputation: 11689

Why not just do

public ActionResult Link(LinkType type)
{
  var obj = ...; //Object that you get from the LinkType. Whatever ShowAString returns.
  return Json(obj);
}

Upvotes: 2

Matt Greer
Matt Greer

Reputation: 62027

Returning an entire view in an AJAX request is almost always not the way to go. Instead you want to return XML, JSON or a chunk of HTML. You can return a chunk of HTML by returning a partial by calling PartialView() in the Controller.

If you are returning HTML, then your jQuery AJAX request needs to be expecting it, so change its dataType to html. Then in the jQuery callback you can just take the received HTML and append it to your page somewhere.

NOTE: you can use Request.IsAjaxRequest() to return either AJAX data or a full view, and use the same action for both kinds of requests. This helps with progressive enhancement.

Upvotes: 4

Austin M
Austin M

Reputation: 604

You are not returning json it looks like you are redirecting to another action that may be returning a view. You will need to set the type of the action to JsonResult and return your json object there.

Upvotes: 1

Related Questions