我想将JsonResult传递给partialView,我能够将JsonResult返回到普通视图,但不知道如何将它传递给局部视图。传递到普通视图的JsonResult是
public JsonResult Search(int id)
{
var query = dbentity.user.Where(c => c.UserId == id);
return Json(query,"Record Found");
}
但想知道如何将其返回到部分视图,例如
public JsonResult Search(int id)
{
var query = dbentity.user.Where(c => c.UserId == id);
return PartialView(query,"Record Found");
}
答案 0 :(得分:1)
使用行动:
public ActionResult Search(int id)
{
var query = dbentity.user.Where(c => c.UserId == id);
return PartialView(query);
}
并在视图中将Model转换为Json对象
<script>
var model = @Html.Raw(Json.Encode(Model))
</script>
答案 1 :(得分:0)
根据您的评论
我想将JsonResult返回到partialView,如返回Json(PartialView,查询) - user3026519 2013年11月24日10:40
我假设你想要返回包含渲染部分视图的Json结果?话虽如此,您可以使用create helper方法将视图转换为字符串,然后将其传递给Json结果。以下是一个可能的解决方案:
你的助手方法:
/// <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();
}
致电行动:
public ActionResult Search(int id)
{
var query = dbentity.user.Where(c => c.UserId == id);
return Json(RenderViewToString(this.ControllerContext, "Search", query));
}