user3026519
user3026519

Reputation: 543

How to pass JsonResult to PartialView in asp.net mvc

I want to pass JsonResult to partialView, I am able to return JsonResult to normal view but do not know how it can be passed to partial view. JsonResult which is being passed to normal view is

public JsonResult Search(int id)
{
    var query = dbentity.user.Where(c => c.UserId == id);
    return Json(query,"Record Found");
}

but want to know how it cant be returned to partial view such as

public JsonResult Search(int id)
{
   var query = dbentity.user.Where(c => c.UserId == id);
   return PartialView(query,"Record Found");
}

Upvotes: 0

Views: 2264

Answers (2)

usr4896260
usr4896260

Reputation: 1507

Based on your comment

I want to return JsonResult to partialView something like return Json(PartialView,query) – user3026519 Nov 24 '13 at 10:40

I'm assuming you want to return Json result containing a rendered partial view? That being said you can use create helper method to convert the view into a string and then pass it to the Json result. Below is a possible solution:

Your helper method:

/// <summary>
/// Helper method to render views/partial views to strings.
/// </summary>
/// <param name="context">The controller</param>
/// <param name="viewName">The name of the view belonging to the controller</param>
/// <param name="model">The model which is to be passed to the view, if needed.</param>
/// <returns>A view/partial view rendered as a string.</returns>
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();
    }

Calling the action:

public ActionResult Search(int id)
{
    var query = dbentity.user.Where(c => c.UserId == id);
    return Json(RenderViewToString(this.ControllerContext, "Search", query));
}

Upvotes: 0

user2984635
user2984635

Reputation: 36

Use action:

public ActionResult Search(int id)
{
   var query = dbentity.user.Where(c => c.UserId == id);
   return PartialView(query);
}

And on view convert Model into Json object

<script>
var model = @Html.Raw(Json.Encode(Model))
</script>

Upvotes: 1

Related Questions