Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I return a ViewBag property to Ajax success callback?

I am calling an MVC controller from ajax. The controller is supposed to return a ViewBag property called Counter:

public ActionResult GetSomething()
{
    var someModel = ...

    ViewBag.Counter = 5;

    return PartialView("SomePartialView", someModel);
}

I call the controller via ajax. What I want is to get access to the ViewBag property called Counter inside the ajax success callback. Is this possible?

$.ajax({
    type: "POST",
    url: "/GetSomething",
    content: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
       // How can I access Counter from here
    },
});

PS: Returning Counter in a model from the controller is not an option. Is must be in a ViewBag.

UPDATE:

Updated the controller with a return value, to let you know, that I cannot return the Counter in a Json.

Solution:

I ended up rewriting my controller like this:

public JsonResult GetHeaderBasketPreview()
{
    var someModel = ...

    return Json(new { pViewHtml = HtmlHelpers.RenderViewToString(this.ControllerContext, "SomePartialView", someModel), counter = 5 });
}

It now returns the html for my partial, plus my counter variable.

RenderViewToString looks like this (I found this helper method in an answer on stackoverflow - but don't remember where):

public static string RenderViewToString(ControllerContext context, string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = context.RouteData.GetRequiredString("action");

    var viewData = new ViewDataDictionary(model);

    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
        var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

I can now access both variables in my ajax success callback:

success: function (data, status, xhr) {
    $('#somePartialView').html(data.pViewHtml);
    $('#counterIndicator').html(data.counter);
}
like image 978
brinch Avatar asked Mar 12 '23 04:03

brinch


2 Answers

That's not a possibility as the data parameter is simply a string of HTML which is generated when you do PartialView("SomePartialView", someModel)

One option is the following:

Within your controller action add Response.Headers["Counter"] = 5

Within your ajax.success, take in two extra parameters status and xhr so that your success function looks like this:

success: function (data, status, xhr) {

After this you can use xhr.getResponseHeader("Counter") which will give you 5 (or whatever you choose to pass in)

like image 107
FLSH Avatar answered Apr 02 '23 18:04

FLSH


Please use your return syntax from your action like this way ...

return Json(new { success = ViewBag.Counter }, JsonRequestBehavior.AllowGet);

Get the response on your view like this ...

success: function (data) {
                     alert(data.success); 
                       },
like image 31
Banwari Yadav Avatar answered Apr 02 '23 19:04

Banwari Yadav