Skip to main content

ASP.NET MVC controller actions that return JSON or partial html


I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?



Source: Tips4allCCNA FINAL EXAM

Comments

  1. In your action method, return Json(object) to return JSON to your page.

    public ActionResult SomeActionMethod() {
    return Json(new {foo="bar", baz="Blech"});
    }


    Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as

    <%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>


    SomeMethod would be a javascript method that then evaluates the Json object returned.

    If you want to return a plain string, you can just use the ContentResult:

    public ActionResult SomeActionMethod() {
    return Content("hello world!");
    }


    ContentResult by default returns a text/plain as its contentType.
    This is overloadable so you can also do:

    return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");

    ReplyDelete
  2. NathanD,

    I think you should consider the AcceptTypes of the request. I am using it in my current project to return the correct content type as follows.

    Your action on the controller can test it as on the request object

    if (Request.AcceptTypes.Contains("text/html")) {
    return View();
    }
    else if (Request.AcceptTypes.Contains("application/json"))
    {
    return Json( new { id=1, value="new" } );
    }
    else if (Request.AcceptTypes.Contains("application/xml") ||
    Request.AcceptTypes.Contains("text/xml"))
    {
    //
    }


    You can then implement the aspx of the view to cater for the partial xhtml response case.

    Then in jQuery you can fetch it passing the type parameter as json:

    $.get(url, null, function(data, textStatus) {
    console.log('got %o with status %s', data, textStatus);
    }, "json"); // or xml, html, script, json, jsonp or text


    Hope this helps
    James

    ReplyDelete
  3. Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

    public ActionResult SomeActionMethod(int id)
    {
    return Json(new {foo="bar", baz="Blech"});
    }


    method from the jquery getJSON method by simply...

    $.getJSON("../SomeActionMethod", {
    id: someId
    },
    function(data) {
    alert(data.foo);
    alert(data.baz);}

    ReplyDelete
  4. To answer the other half of the question, you can call:

    return PartialView("viewname");


    when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.

    ReplyDelete
  5. You may want to take a look at this very helpful article which covers this very nicely!

    Just thought it might help people searching for a good solution to this problem.

    http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx

    Paul

    ReplyDelete
  6. For folks who have upgraded to MVC 3 here is a neat way
    Using MVC3 and Json

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.