0

在我的 MVC 网站中,我正在创建一个小型论坛。对于单个帖子,我在我的“PostController”中呈现我的“Single(Post post)”操作,如下所示

<% Html.RenderAction<PostController>(p => p.Single(comment)); %>

此外,当用户回复帖子时,我将回复作为 ajax 请求发送到我的“CreatePost”操作,然后返回“Single”视图作为此操作的结果,如下所示

public ActionResult CreatePostForForum(Post post)
{
    //Saving post to DB
    return View("Single", postViewData);
}

当我喜欢只呈现视图时,“单一”动作主体中的代码不会被执行。

做这个的最好方式是什么?

我还想在我的 JsonObject 中将“Single”操作结果作为字符串返回,如下所示

return Json(new{IsSuccess = true; Content= /*HERE I NEED Single actions result*/});
4

2 回答 2

0

您可以使用类似的东西,但要非常小心。它实际上会导致严重的可追溯错误(例如,当您忘记在 Single 方法中显式设置视图名称时)。

public ActionResult Single(PostModel model) {
    // it is important to explicitly define which view we should use
    return View("Single", model);
}

public ActionResult Create(PostModel model) {

    // .. save to database ..

    return Single(model);
}

更清洁的解决方案是像从标准表单发布一样做同样的事情 - 重定向(XMLHttpRequest 将跟随它)

为了返回包装在 json 中的 ajax 视图,我使用以下类

public class AjaxViewResult : ViewResult
{
    public AjaxViewResult()
    {

    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (!context.HttpContext.Request.IsAjaxRequest())
        {
            base.ExecuteResult(context);
            return;
        }

        var response = context.HttpContext.Response;

        response.ContentType = "application/json";

        using (var writer = new StringWriter())
        {
            var oldWriter = response.Output;
            response.Output = writer;
            try
            {
                base.ExecuteResult(context);
            }
            finally
            {
                response.Output = oldWriter;
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            response.Write(serializer.Serialize(new
            {
                action = "replace",
                html = writer.ToString()
            }));
        }
    }
}

这可能不是最好的解决方案,但效果很好。请注意,您需要手动设置 View、ViewData.Model、ViewData、MasterName 和 TempData 属性。

于 2011-03-14T23:19:19.860 回答
0

我的建议:

  • 通过 Ajax 发布您的论坛回复(以及任何选项)。
  • 返回您的 JSONResult,使用此方法:ASP MVC View Content as JSON以呈现您的内容。
  • 在 ajax 调用的 OnSuccess 处理程序中,检查 IsSuccess 是否为真。如果成功,则使用 JQuery 将内容附加到适当的容器中
于 2011-03-14T23:35:02.460 回答