2013-03-23 34 views
7

所以我有一個可行的方法完成,我用它在整個網站:ASP.NET MVC呈現局部視圖將一個字符串與JSON返回

public PartialViewResult GetBlogEntries(int itemsToTake = 5) 
{ 
    ... 
    return PartialView("_BlogPost", model); 
} 

現在我想從我的javascript得到這以JSON形式。

public JsonResult GetBlogPostJson() 
{  
    var blogEntry = GetBlogEntries(1); 
    var lastEntryId = GetLastBlogEntryId(); 
    return Json(new {Html = blogEntry, LastEntryId = lastEntryId}, JsonRequestBehavior.AllowGet); 
} 

想法是讓這樣的:

$.ajax({ 
      url: '/Blog/GetBlogPostJson', 
      dataType: 'json', 
      success: function (data) { 
       var lastEntryId = data.LastEntryId; 
       var html = data.Html; 
       ... 
      } 
     }); 

問題是,這當然是不產生一個字符串,而是一個PartialViewResult。

問題是,我該如何將PartialViewResult解析爲html,我可以用JSON發回?

+0

請糾正我,如果我錯了,你想生成HTML,然後從這個HTML獲得一個ID,並最終發送ID和HTML在JSON? – Dima 2013-03-23 15:30:40

+0

是的,沒有。方法GetBlogEntries()創建一個局部視圖,我從網頁上的各個地方調用。但它不會在任何地方打印出ID。所以我需要單獨獲取它。然後將html和id發送給調用者。如果有任何新的博客條目,客戶端上的JavaScript將確保只獲取新的博客條目。 – Patrick 2013-03-23 15:39:02

+0

@NickLarsen,請再次查看您標記爲重複的問題和答案。這個問題要求以JSON的形式返回View(比如從結束點),而其他的要求Razor渲染。類似的,是的。但絕對不是相同的用例。 – 2016-07-18 00:56:29

回答

16

大約6個月前我經歷了這個。目標是使用部分填充jquery彈出對話框。

問題是視圖引擎想使它們在自己的尷尬爲了...

試試這個。 LMK如果需要澄清。

public static string RenderPartialViewToString(Controller thisController, string viewName, object model) 
    { 
     // assign the model of the controller from which this method was called to the instance of the passed controller (a new instance, by the way) 
     thisController.ViewData.Model = model; 

     // initialize a string builder 
     using (StringWriter sw = new StringWriter()) 
     { 
      // find and load the view or partial view, pass it through the controller factory 
      ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(thisController.ControllerContext, viewName); 
      ViewContext viewContext = new ViewContext(thisController.ControllerContext, viewResult.View, thisController.ViewData, thisController.TempData, sw); 

      // render it 
      viewResult.View.Render(viewContext, sw); 

      //return the razorized view/partial-view as a string 
      return sw.ToString(); 
     } 
    } 
+0

像魅力一樣工作。謝謝=) – Patrick 2013-03-23 15:41:34

+0

我如何通過(控制器thisController),你能告訴我我將如何使用你的方法? – 2013-09-03 19:54:42

+0

這個工作,但它不是單元測試。 :( – 2014-07-21 20:44:11

相關問題