MVC Widget JsonResult Question

Posted by Community Admin on 04-Aug-2018 14:35

MVC Widget JsonResult Question

All Replies

Posted by Community Admin on 20-Jul-2012 00:00

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

Posted by Community Admin on 02-Aug-2012 00:00

Hi everyone.
So sad. Looks like it's impossible. I'm just using wcf for ajax requests.

Posted by Community Admin on 07-Aug-2012 00:00

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

Posted by Community Admin on 15-Aug-2012 00:00

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);
    
);

Posted by Community Admin on 15-Aug-2012 00:00
Posted by Community Admin on 27-Sep-2012 00:00

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);

Posted by Community Admin on 12-Dec-2013 00:00

Hi,

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

Has anybody managed to get a fix for this?

Posted by Community Admin on 12-Dec-2013 00:00

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())
        


Posted by Community Admin on 12-Dec-2013 00:00

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;

Posted by Community Admin on 12-Dec-2013 00:00

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

Posted by Community Admin on 12-Dec-2013 00:00

Thank you Victor, That was what i was after! All working now

Cheers
Andrew

Posted by Community Admin on 01-Jan-2014 00:00

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.

Posted by Community Admin on 06-Jan-2014 00:00

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

Posted by Community Admin on 12-Jan-2014 00:00

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?

Posted by Community Admin on 16-Jan-2014 00:00

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

Posted by Community Admin on 18-May-2015 00:00

Thank you Victor, this simple solution resolved the problem for me.

Posted by Community Admin on 25-Aug-2017 00:00

@Stanislav does Bootstrap.MVC still apply? Intellisense recognizes Bootstrap from the Telerik.Sitefinity.Abstracts assembly but it doesn't recognize MVC. 

Does it have to be done with Bootstrapper or will the regular routes.MapHttpRoute work? 

This thread is closed