MVC Widget JsonResult Question - Front- & Back-End Development - Front- & Back-End Development - Progress Community
 Front- & Back-End Development

MVC Widget JsonResult Question

  • MVC Widget JsonResult Question
  • 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
  • Hi everyone.
    So sad. Looks like it's impossible. I'm just using wcf for ajax requests.
  • 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
  • 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);
        
    );
  • Controller can be used for ajax requests in classic mode. Here described how to register route:
    http://www.sitefinity.com/documentation/documentationarticles/developers-guide/sitefinity-essentials/how-does-sitefinity-use-asp.net-mvc/three-mvc-modes/classic-mode
  • 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);
  • Hi,

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

    Has anybody managed to get a fix for this?

  • 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;
  • Thank you Victor, That was what i was after! All working now

    Cheers
    Andrew
  • 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())
            


  • 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
  • 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.
  • 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
  • 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?