简体   繁体   中英

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM