2013-08-20 36 views

回答

30

當然,將以下方法放在共享控制器或助手類中。它會返回HTML渲染視圖,使用自explainatory:

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(); 
     } 
    } 
+1

你真棒天才男人! :) –

+0

@Leo Nix我應該如何創建上下文參數?我試圖初始化一個實例,但我不知道它的構造函數的ControllerBase參數。 – Hosein

+0

如果您在上下文中使用控制器操作,則不需要創建一個:ControllerContext是控制器的屬性,因此只需將其傳入。https://goo.gl/pp5AkR –

6

我不知道這是否是最好的做法或沒有,但如果u離開它,因爲它是

return PartialView("_Product", model) 

然後你叫這個方法用阿賈克斯

$.ajax ({ 
    type: "POST", 
     url: _url, 
     data: _data, 
     success: function (result) { 
      // the result is the returned html from the partial view 
     } 
})