Can I return a ViewBag property to Ajax success callback?
<p>I am calling an MVC controller from ajax. The controller is supposed to return a ViewBag property called Counter:</p>

<pre><code>public ActionResult GetSomething()
{
    var someModel = ...

    ViewBag.Counter = 5;

    return PartialView("SomePartialView", someModel);
}
</code></pre>

<p>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?</p>

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

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

<p>UPDATE:</p>

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

<p><strong>Solution:</strong></p>

<p>I ended up rewriting my controller like this:</p>

<pre><code>public JsonResult GetHeaderBasketPreview()
{
    var someModel = ...

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

<p>It now returns the html for my partial, plus my counter variable.</p>

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

<pre><code>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();
    }
}
</code></pre>

<p>I can now access both variables in my ajax success callback:</p>

<pre><code>success: function (data, status, xhr) {
    $('#somePartialView').html(data.pViewHtml);
    $('#counterIndicator').html(data.counter);
}
</code></pre>