+1-888-365-2779
Try Now
More in this section

Forums / Developing with Sitefinity / MVC Widget JsonResult Question

MVC Widget JsonResult Question

16 posts, 0 answered
  1. Ryan
    Ryan avatar
    2 posts
    Registered:
    16 Jul 2012
    20 Jul 2012
    Link to this post
    Hey everybody

    I have a question regarding using JsonResult in an MVC widget. Here's the scenario:

    My link is localhost/home/widget/testjson/test --> where test being the ID string passed into the JsonResult method. 

    Now, the query successfully works, but here's the problem: the json is wrapped in my sitefinity template.

    Here's an example:

    {"Text":"test"}<!DOCTYPE html>
     
    <head>
     
        <link rel="stylesheet" href="/WebResource.axd?d=mkv_SJnA-bKem_u4J2vFD1i8i_6WSrF0tR1nGIeC6ouygQovkjBlJVldUHX3i7xZUA3eRNjF8xA1v5AXW9-6pOy3W0n9YY6nbTv5IM90jny2yRzKZm8SSx-HWyWrJXoAiK3A7GWJyGZMWgrA0OVMEZFyB-nvQ1-LoPND3nmz_cWKLDE55ZgP1GqLeR6ffyzT0&t=634780453720000000" type="text/css" />
     
        <link rel="stylesheet" href="/WebResource.axd?d=Qoo0u_dnGSaTmRcZf6J_Uu5e7kVbgj_LowHHsVu__CWGamAUCypd8xriRYaj1GrraCKeJ2dN3qufDIKj2s-P-kRuM7CkQaw_zIPJbj1WSo5_nao0SXLxx2dRRJrwEoKyeoutcWCTeuHaTwGAaE1XBkPySQfV5rpPkebX6FkbU0CL_VMU9-5jjWXjalYuvsp4aKJU_YSWtwSmHzgwot-JjA2&t=634780453720000000" type="text/css" />
     
        <link rel="stylesheet" href="/WebResource.axd?d=eVmonh6wPIg6sx5oER4CsRdPNrelAT7zJWZRvJROPyWdwhohktx6WYuTWoVpqfCTVHwH-w1I5uZRqva2UJG90upZHl_8ewdJrgRMUyelTwd2zxwiiuquc2-xkKPfqikKEV6GkBqklmbLHTwSU7e_HXobHeOcQrLCkSODB_7ZvLlC0Jwsgu94pYHKl9kJ0ixz0oPI3HLisQb950xp8q71mQ2&t=634780453720000000" type="text/css" />
     
        <meta name="Generator" content="Sitefinity 5.1.3210.0 CE" />
     
        <title>Home</title>
     
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
     
    </head>
     
    <body>
     
        <div class="sfPublicWrapper" id="PublicWrapper">
     
        </div>
     
    </body>
     
                            <p style="overflow: visible ! important; text-align: center ! important; display: block ! important; visibility: visible ! important; position: static ! important;" class="poweredBySitefinity">
     
                                <a rel="external" href="http://www.sitefinity.com" style="display: inline ! important; visibility: visible ! important; position: static ! important; border: 0 !important;" title="Sitefinity Web Content Management System">
     
                                    <img width="107" height="51" style="display: inline ! important; visibility: visible ! important; position: static ! important; width: 107px ! important; border: 0 !important; height: 51px ! important;" alt="Sitefinity Web Content Management" src="/WebResource.axd?d=2T9Zxr7smMD-RtVobUGsMjDAPZd-dwuxxgZk9fJ-TdwyrfvrI9q9ojCOujToMhulyJFfLl7e0a_PzOeGJWWwpaHgFF947yYDrMHdO4dKHJWlkpSXZZZvn_LfaPCeLzqxSzb9O-I2thX0YiDEz7XdYRWwycdvWBg_M7HRdWtG4zE1&t=634780453720000000"/>
     
                                </a>
     
                            </p>
     
    </html>

    Is it possible to return JUST the Json data and not the page code? I have seen solutions where people write services in addition to the MVC widget, but honestly that defeats the purpose of using MVC in my mind. 

    Please help me out!

    Thanks,

    RC
  2. Andrey
    Andrey avatar
    10 posts
    Registered:
    18 Jul 2012
    02 Aug 2012
    Link to this post
    Hi everyone.
    So sad. Looks like it's impossible. I'm just using wcf for ajax requests.
  3. Stanislav Velikov
    Stanislav Velikov avatar
    1113 posts
    Registered:
    30 Nov 2016
    07 Aug 2012
    Link to this post
    Hello,

    It is possible to get data which in this case is the json data from the View to the Controller and then use it as route parameter ID.
    Refer to this thread which discusses how this is done.

    All the best,
    Stanislav Velikov
    the Telerik team
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  4. Andrey
    Andrey avatar
    10 posts
    Registered:
    18 Jul 2012
    15 Aug 2012
    Link to this post
    Hi Stanislav.
    It's not about routing. It's about ajax requests and json results.
    For example ajax request below not working with controller, because every controller response decorated by html tags (you can see it in Ryan post).
    $.ajax({
        type: "GET",
        cache: false,
        url: serviceUrlHelper.configServiceBaseUrl + '/Load',
        success: function (result) {
            merchantUsername.val(result.Username);
            merchantPassword.val(result.Password);
            apiKeyInput.val(result.ApiKey);
        }
        error: function(jqXHR, textStatus, errorThrown) {
            handleException(jqXHR, textStatus, errorThrown);
        }
    });
  5. Andrey
    Andrey avatar
    10 posts
    Registered:
    18 Jul 2012
  6. Francisco
    Francisco avatar
    7 posts
    Registered:
    14 Sep 2010
    27 Sep 2012
    Link to this post
    hello;
    I have the same problem, the returns with html of the page.

    with this method return:
    public JsonResult GetPrueba(string id)
    {
       return Json(id);
    }
  7. Andrew Wiseman
    Andrew Wiseman avatar
    4 posts
    Registered:
    24 May 2006
    12 Dec 2013
    Link to this post
    Hi,

    I seem to be getting the same results as described by Ryan.

    Has anybody managed to get a fix for this?

  8. Francisco
    Francisco avatar
    7 posts
    Registered:
    14 Sep 2010
    12 Dec 2013 in reply to Andrew Wiseman
    Link to this post
    Hi Andrew,
    the solution was to add the following code in the Global.asax
    Bootstrapper.MVC.MapRoute(
                    "Classic",
                    "JSON/{controller}/{action}",
                     new { action = "Index" });
     
                Bootstrapper.MVC.MapRoute(
                   "ClassicAjax",
                   "AJAX/{controller}/{action}",
                    new { action = "Index" });

    Example jquery:
    function fechaInicio(textoFecha) {
                $.post("/./JSON/CalendarioController", $(".FechaSelect").val())
            }


  9. Victor
    Victor avatar
    94 posts
    Registered:
    15 Jun 2011
    12 Dec 2013
    Link to this post
    Try this.
    Put the following code in the controller:
    bool dontShowPageData;
    protected override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if (dontShowPageData)
        {
    Response.End();
        }
        base.OnResultExecuted(filterContext);
    }

    Now, right before you return your JSON, just put this line:
    dontShowPageData = true;
  10. Andrew Wiseman
    Andrew Wiseman avatar
    4 posts
    Registered:
    24 May 2006
    12 Dec 2013 in reply to Francisco
    Link to this post
    Hi Francisco,

    Thank you for the quick reply! Unfortunately i'm still have a problem with setting this up.

    I have managed to set up the global.asax  but the route path is some thing that is confusing me. 

    The page that the widget is hosted on domain.com/test and i have the following:

    Global.asax
    protected void Application_Start(object sender, EventArgs e)
            {
                Bootstrapper.MVC.MapRoute(
                    "Classic",
                    "AccountRegistrationController/SaveAccountDetails",
                    new { action = "SaveAccountDetails" }
                );
            }

    Controller.cs
    namespace SitefinityWebApp.Mvc.Controllers
    {
        [ControllerToolboxItem(Name = "AccountRegistration", Title = "AccountRegistration", SectionName = "Custom")]
        public class AccountRegistrationController : Controller
        {
            /// <summary>
            /// Gets or sets the message.
            /// </summary>
            [Category("String Properties")]
            public string Message { get; set; }
     
            /// <summary>
            /// This is the default Action.
            /// </summary>       
     
            public ActionResult Index()
            {
                var model = new AccountRegistrationModel();
                model.CompanyName = "testName";
                return View("Default", model);
            }
            [HttpPost]
            public ActionResult SaveAccountDetails(AccountRegistrationModel model)
            {
                if (ModelState.IsValid)
                {
                    return Content(MvcHelper.RenderPartialViewToString(this, "Complete", null));
                }
     
                return Content(MvcHelper.RenderPartialViewToString(this, "Default", model));
            }
        }
    }

    Not sure where im going wrong.

    Regards
    Andrew
  11. Andrew Wiseman
    Andrew Wiseman avatar
    4 posts
    Registered:
    24 May 2006
    12 Dec 2013
    Link to this post
    Thank you Victor, That was what i was after! All working now

    Cheers
    Andrew
  12. Jamie
    Jamie avatar
    25 posts
    Registered:
    07 Aug 2012
    01 Jan 2014 in reply to Victor
    Link to this post
    Victor's solution works, thanks! One improvement is to check the response type and put the override into a base controller so that it's seamless.
    /// <summary>
    /// Base controller class containing helpers for dealing with Sitefinity quirks.
    /// </summary>
    public abstract class SitefinityController : Controller
    {
        protected override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            // Prevent the result from being wrapped in the SF page layout
            if (filterContext.Result is JsonResult)
            {
                Response.End();
            }
            base.OnResultExecuted(filterContext);
        }
     
    }

    One minor disadvantage to this approach is that a ThreadAbortException is thrown when Response.End is called. It's handled internally but the debugger with break if break on thrown exceptions is set.
  13. Stanislav Velikov
    Stanislav Velikov avatar
    1113 posts
    Registered:
    30 Nov 2016
    06 Jan 2014
    Link to this post
    Hi,

    The approach to be used in using custom route is described in this blog post.

    Regards,
    Stanislav Velikov
    Telerik
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  14. Jamie
    Jamie avatar
    25 posts
    Registered:
    07 Aug 2012
    12 Jan 2014 in reply to Stanislav Velikov
    Link to this post
    Stanislav, I may be missing your point. Are you saying that declaring a custom json route will allow the action to return JsonResult without any other tricks?
  15. Stanislav Velikov
    Stanislav Velikov avatar
    1113 posts
    Registered:
    30 Nov 2016
    16 Jan 2014
    Link to this post
    Hello,

    Yes the custom route with a designated prefix to service the json route will be used to serve as a route that link to ActionResult that return json datasource from an action.

    This way instead of binding json returning action directly to a control that accepts json data, the route will be bound instead which will serve the json only an not include the whole page Html output.
    .DataSource(ds => ds.Ajax()
            .Read(a => a.Url("/json/employees/listemployees"))

    This is specific to Sitefintiy as its a web forms application that supports MVC by rendering a controller output as html on a web forms page and thus the result from the json returning action is mixed with HTML which is avoided by the above approach.

    Regards,
    Stanislav Velikov
    Telerik
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  16. Mike Strother
    Mike Strother avatar
    1 posts
    Registered:
    26 Oct 2006
    18 May 2015 in reply to Victor
    Link to this post
    Thank you Victor, this simple solution resolved the problem for me.
16 posts, 0 answered