将部分视图返回为字符串

时间:2012-05-27 03:42:42

标签: c# javascript jquery

我正在尝试减少向服务器发出的get请求数。我想将部分视图作为字符串返回到我的$.get方法,以便我可以一次返回3个而不是3个单独的服务器回调。无论如何要做到这一点。到目前为止我有

到目前为止它只返回System.Web.Mvc.PartialViewResult

function updateChat() {

/** I want to make this work so I only have 1 callback */
$.get("Home/refreshChatParts", {}, function (response) {
    var html = response.split(",");
    $("#chatWindow").replaceWith(html[0]);
    $("#chatHeader").replaceWith(html[1]);
    $("#playerList").replaceWith(html[2]);
});

/**  this stuff works, but is a lot of call backs */
$.get("Home/refreshChatText", {}, function (html) {
    $("#chatWindow").replaceWith(html);
});

$.get("Home/refreshChatHeader", {}, function (html) {
    $("#chatHeader").replaceWith(html);
});

$.get("Home/refreshPlayerList", {}, function (html) {
    $("#playerList").replaceWith(html);
});
*/
$.get("Home/getRequest", {}, function (requestUser) {
    if (requestUser.toString() != "failed") {
        pause = true;
        var join = confirm(requestUser + " would like to play a game with you");
        if (join) {
            startGame(requestUser);
        } else
            pause = false;
        resetRequestUser(requestUser);
    }
});

//$.get("Home/checkForGameStart", {}, function (response) { /*alert(response);*/ });

scrollChatDown();

setTimeout('updateChat()', 20000);
}




 public String refreshChatParts() {

        //refresh chat text
        ViewData["ChatText"] = getFormatedChatText();

        //refresh usercount
        try {
            userCount = getUserCount();
            ViewData["numberOfUsers"] = "There are " + userCount + " players online";
        } catch (Exception e) { ViewData["numberOfUsers"] = e.Message; }

        //refresh player list
        ViewData["listOfPlayers"] = getFormatedPlayerList();

        checkForGameStart();

        return PartialView("ChatText") + "," + PartialView("ChatHeader") + "," + PartialView("playerList");
    }

1 个答案:

答案 0 :(得分:0)

方法“PartialView”返回类型“System.Web.Mvc.PartialViewResult”,因此当您尝试连接该方法的返回结果时,它将调用对象的ToString,如果没有覆盖,则只返回类型名称。 / p>

因此,这种方法不适用。您要做的是将您的操作返回类型标记为PartialViewResult。

然后定义一个部分视图,它只写出你想要返回的三个部分视图。

如果你定义一个像这样的新部分:

@{ Html.RenderPartial("ChatText"); } ,
@{ Html.RenderPartial("ChatHeader"); } ,
@{ Html.RenderPartial("playerList"); } 

然后返回那个部分,你应该得到你想要的东西。