Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSON from a JsonResult method in MVC controller

I am trying to populate a ComboBox (Telerik RAD COmboBox) in a test ASP.NET MVC3 app.

I have defined the ComboBox on my ASPX page and in the controller I have defined the action call that returns a JsonResult.

The problem I am having is that the Web Service I am using already returns the resultset as a JSON string. How can I pass the response from the Webservice directly.

Here is the snippets of code: ASPX page:

<% Html.Telerik().ComboBox()
                       .Name("cbRefTables")
                       .DataBinding(b => b
                           .Ajax()
                           .Select("GetCALMdata","Common")                    
                       )
                       .Render();
                %>

Controller: called CommomController

    public JsonResult GetCALMdata()
    {
        CALMwsP.wsCALMSoapClient wsC = new CALMwsP.wsCALMSoapClient("wsCALMSoap");
        string resultset = wsC.GetRefTables("P_1", "P_2", "P_3", "P_4");

        return ??; -- I want to return resultset which is already formatted. 
    }
like image 288
MAB Avatar asked May 05 '11 16:05

MAB


People also ask

What does JsonResult return?

JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

How do I return a view in JsonResult?

You just have toinclude html(view) as one of the property in your json data. @Zach Yes, It's possible. You can return your html with model. Create a partial view and return the partial view with model instead of json result.


2 Answers

If using ASP.NET MVC 2 or higher:

return Json(resultset, JsonRequestBehavior.AllowGet);
like image 54
alexl Avatar answered Sep 17 '22 13:09

alexl


If the resultset string is already JSON (and not wrapped in any XML), then you'd want to return a ContentResult with exactly that string as the content:

public ContentResult GetCALMdata()
{
    CALMwsP.wsCALMSoapClient wsC = new CALMwsP.wsCALMSoapClient("wsCALMSoap");
    string resultset = wsC.GetRefTables("P_1", "P_2", "P_3", "P_4");

    return Content(resultset, "application/json");
}

You don't want to use JsonResult or the Json() helper in this case, because that's going to end up re-serializing your JSON.

like image 28
Dave Ward Avatar answered Sep 18 '22 13:09

Dave Ward