以字符串形式返回其他操作结果
在我的 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 中的字符串返回,如下所示
return Json(new{IsSuccess = true; Content= /*HERE I NEED Single actions result*/});
In my MVC website, I am creating a small forum. For a single post I am rendering my "Single(Post post)" action in my "PostController" like below
<% Html.RenderAction<PostController>(p => p.Single(comment)); %>
Also When a user reply a post I am sending reply as an ajax request to my "CreatePost" action then return "Single" view as result of this action like below
public ActionResult CreatePostForForum(Post post)
{
//Saving post to DB
return View("Single", postViewData);
}
When I do like that only the view is being rendered, Codes in "Single" Actions body isn't beig executed.
What is the best way to do this?
Also I want to return "Single" action result as string in my JsonObject like below
return Json(new{IsSuccess = true; Content= /*HERE I NEED Single actions result*/});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用类似的东西,但要非常小心。它实际上可能会导致严重的可追溯错误(例如,当您忘记在 Single 方法中显式设置视图名称时)。
更干净的解决方案是像从标准表单发布一样 - 重定向(XMLHttpRequest 将遵循它)
为了返回包装在 json 中的 ajax 视图,我使用以下类
它可能不是最好的解决方案,但它工作得很好。请注意,您需要手动设置 View、ViewData.Model、ViewData、MasterName 和 TempData 属性。
You can use something like this, but be very careful with this. It can actually cause badly traceable errors (for example when you forget to explicitly set view name in Single method).
Cleaner solution would be to do the same as if it was post from standard form - redirect (XMLHttpRequest will follow it)
For returning ajax views wrapped in json I use following class
It is probably not the best solution, but it works quite well. Note that you will need to manually set View, ViewData.Model, ViewData, MasterName and TempData properties.
我的建议:
My recommendation: