Returning JSON from a JsonResult method in MVC controller

旧街凉风 提交于 2019-11-30 03:23:22

问题


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. 
    }

回答1:


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.




回答2:


If using ASP.NET MVC 2 or higher:

return Json(resultset, JsonRequestBehavior.AllowGet);



回答3:


if I correctly understood you should use the Json() method

return Json(resultset);



回答4:


The individual Json Method:

return Json(resultset);

It needs the System.Web.Http DLL and the namespace is System.Web.Http.Results.


Or Website wide put this line in the WebApiConfig.cs

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));


来源:https://stackoverflow.com/questions/5901411/returning-json-from-a-jsonresult-method-in-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!