Asp.Net Mvc 2 - RenderAction List with a create
First, I use Asp.Net MVC 2 RC 2.
What I want to do is to list a comment view and below this view being able to add comment (with validations). For example, something like when you add comment in stackoverflow. Except that my page should work with or without javascript enabled.
So to solve that problem I use the new RenderAction and it partially solved my problem. I got my list view that calls my addcomment usercontrol with RenderAc开发者_StackOverflow中文版tion.
The validations work. My problem occurs when I try to add a comment that it's valid. The page didn't refresh correctly. If I got in the database, my comment is added, but it's doesn't have been refresh in my list view and the add comment form isn't clear.
I think it's because of how the workflow is rendered.
Maybe if someone got a example or blog about this, it's can help me to get it right...
At the bottom of my Comment/List.aspx
<% Html.RenderAction("Create", "Comment"); %>
In Comment/Create.ascx
<% using (Html.BeginForm(
ViewContext.ParentActionViewContext.RouteData
.Values["action"].ToString(),
ViewContext.ParentActionViewContext.RouteData
.Values["controller"].ToString(),
FormMethod.Post, new { id = "createForm" })){ %>
You can force the parent View to refresh itself with a small hack involving ViewContext.ParentActionViewContext.
In your CommentController class:
public ActionResult Create(Comment comment)
{
...
if (isValid) // Comment entered in form is valid
{
ControllerContext.ParentActionViewContext.ViewData["SuccessfullCreate"] = true;
}
...
}
And in your Comment/List.aspx page (view) :
<% Html.RenderAction("Create", "Comment"); %>
<%
if (ViewContext.ViewData["SuccessfulCreate"] != null)
{
string action = ViewContext.RouteData.Values["action"].ToString();
string controller = ViewContext.RouteData.Values["controller"].ToString();
string url = "/" + controller + "/" + action;
Response.Redirect(url);
}
%>
So basically, what's happening is that the child action is "telling" the parent action to refresh itself by using the parent's ViewData.
It's kind of a hack, but it works fine for what's you're doing.
精彩评论