开发者

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

开发者 https://www.devze.com 2023-02-02 09:57 出处:网络
So I have an MVC Action in my controller public System.Web.Mvc.ActionResult Link(LinkType type) { switch (type)

So I have an MVC Action in my controller

public System.Web.Mvc.ActionResult Link(LinkType type)
        {
            switch (type)
            {
                case LinkType.IC:
                    return RedirectToAction("开发者_Go百科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?


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.


Why not just do

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消