2013-11-24 42 views
0

我想將JsonResult傳遞給partialView,我可以將JsonResult返回到普通視圖,但不知道如何將它傳遞給局部視圖。它被傳遞到普通視圖JsonResult是如何將JsonResult傳遞給asp.net中的PartialView mvc

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

根據定義,代碼'返回PartialView(查詢 「符合條件的記錄」)'包含2參數,第一個應該是視圖名稱,第二個應該是模型類型。還有兩個重載方法包含模型或視圖名稱。 – Twocode

+0

控制器操作只能返回一種類型的操作結果。你的目標是什麼? –

+0

我想返回JsonResult到partialView類似於返回Json(PartialView,查詢) – user3026519

回答

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> 
0

基於您的評論

我想返回JsonResult到partialView像返回JSON(PartialView,查詢) - 10:40

user3026519 11月24日'13我假設你想返回JSON包含渲染的局部視圖的結果?這就是說你可以使用create helper方法將視圖轉換爲字符串,然後將它傳遞給Json結果。下面是一個可能的解決方案:

你的helper方法:

/// <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)); 
} 
相關問題