7

だから私は機能する完成した方法を持っていて、それをウェブサイト全体で使用しています:

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

今、私はJSON形式で私のjavascriptからこれを取得したい.

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 を JSON で返送できる html に解決するにはどうすればよいですか?

4

1 に答える 1

16

私は約6ヶ月前にこれを経験しました。目標は、パーシャルを使用して jquery ポップアップ ダイアログに入力することでした。

問題は、View Engine がそれらを独自の厄介な順序でレンダリングしたいということです...

これを試して。明確化が必要な場合は 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();
        }
    }
于 2013-03-23T15:30:15.500 に答える