【问题标题】:How to pass JsonResult to PartialView in asp.net mvc如何将 JsonResult 传递给 asp.net mvc 中的部分视图
【发布时间】:2013-11-24 09:09:43
【问题描述】:

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

【问题讨论】:

  • 根据定义,您的代码 return PartialView(query,"Record Found") 包含 2 个参数,第一个应该是视图名称,第二个应该是模型类型。还有两个重载方法包含模型或视图名称。
  • 一个控制器动作只能返回一种类型的动作结果。你的目标到底是什么?
  • 我想将 JsonResult 返回到 partialView 之类的 return Json(PartialView,query)
  • 您使用错误的返回类型更改来抽象 ActionList
  • 为什么不将渲染的局部视图返回为 jsonobject。用你的模型渲染你的部分视图并返回结果,在从 jquery 获得结果后,用新的渲染字符串更改控件的 html。

标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

使用动作:

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

并在视图上将模型转换为 Json 对象

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

【讨论】:

    【解决方案2】:

    根据您的评论

    我想将 JsonResult 返回到 partialView,例如 return Json(PartialView,query) – 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));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 2013-07-14
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多