简体   繁体   中英

.net mvc show “saved” message in strongly typed parent view when child form save complete

I have a blog object which can contain comment objects.

Currently, the blog contains the blog info and also a partial that renders a list of comments and the form to add a new comment. This comment form posts to a Save action in my Comment controller and then redirects back to the Show action of the Blog controller. The below code is the action action.

        //the id of the blog this comment is for
        int blogId;
        bool parsed = Int32.TryParse(Request.Form["blogId"].ToString(), out blogId);

        //get the blog
        BlogService blogService = new BlogService(unitOfWork);
        Blog blog = new Blog();

        if (parsed)
        {
            blog = blogService.GetBlogArticle(blogId);
        }

        //setup up our comment
        CommentService service = new CommentService(unitOfWork);
        Comment comment = model;
        comment.Blog = blog;

        //set the comment date
        comment.PostedDate = DateTime.Now;

        bool actionSucceeded = true;
        string errorMessage = "Something went wrong. Please try your request again.";

        try
        {
            service.Add(comment);
            unitOfWork.Save();  
        }
        catch
        {
            actionSucceeded = false;
        }

        if (actionSucceeded)
        {
            TempData["ActionMessage"] = "Comment successfully added. Comments need approval before being posted.";
            return RedirectToAction("show", "blog", new { id = comment.Blog.Id });
        }
        else
        {
            ModelState.AddModelError(string.Empty, errorMessage);
        }

        return RedirectToAction("show", "blog", new { id = comment.Blog.Id });

My Comment View Model is setup like this.

public class CommentListModel
{
    public IEnumerable<Comment> Comments { get; set; }
    public string ActionMessage { get; set; }
}

And my Blog View Model is setup like this.

public class BlogModel : ResultsModel<Blog>
{
    public Blog Blog { get; set; }
    public string ActionMessage { get; set; }

    public BlogModel() : base()
    {
        this.ItemsPerPageOptions = new KeyValuePair<int, string>[]
        {
            new KeyValuePair<int, string>(15, "Items Per Page: 15"),
            new KeyValuePair<int, string>(20, "Items Per Page: 20"),
            new KeyValuePair<int, string>(25, "Items Per Page: 25"),
            new KeyValuePair<int, string>(30, "Items Per Page: 30"),
            new KeyValuePair<int, string>(40, "Items Per Page: 40"),
            new KeyValuePair<int, string>(50, "Items Per Page: 50")
        };
    }
}

And the portion of the View that handles this.

   @if (TempData["ActionMessage"] != null)
        {   
            <div class="validation-summary-success" style="font-size: 2.1em; color: gray; background-color: #90EE90; padding: 10px; margin:2px;">
                <ul>
                    <li>@TempData["ActionMessage"]</li>
                </ul>
            </div>

            <script type="text/javascript">
                $(".validation-summary-success").delay(3000).fadeOut("slow").slideUp("slow");
            </script>   
        }

        <div class="Head">
          <h5>@Model.Blog.Title</h5>
          <label>By: @Model.Blog.Admin.Name <span>|  @Model.Blog.PostingDate.ToShortDateString()</span></label>
        </div>
        <article class="mContent">
            <p>@Model.Blog.Body</p>   
        </article>
        <div id="commentContainer">
                @Html.Partial("_BlogComments", @Model.Blog.Comments, new ViewDataDictionary { {"blogId", @Model.Blog.Id}  })
        </div>

As you can see, I'm using the TempDataDictionary to show a "Saved" message. However, it is my understanding that this defeats the purpose of having a strongly typed view.

When I save this comment in the Save action, how do I set the ActionMessage property if I am redirecting back to the Show action of the Blog controller if this action currently accepts a record ID? Would I set the ActionMessage property of the Blog or Comment object?

I would use an Ajax form to post the new comment and get the status message. There's no need to re-send the whole page for a single comment update, right? It looks like you could even return the status message as text, and update the status field using UpdateTargetId .

@using Ajax.BeginForm("Save", "Comment", new AjaxOptions() {
    HttpMethod = "POST",
    UpdateTargetId = "StatusContainer",
    OnSuccess = "FadeOutStatus",
}) {
    <input type='submit' value='Add Comment' />
}

<div class="validation-summary-success" style="display: none; font-size: 2.1em; color: gray; background-color: #90EE90; padding: 10px; margin:2px;">
    <ul>
        <li><span id="StatusMessage"></span></li>
    </ul>
</div>

<script type="text/javascript">
    $(".validation-summary-success").fadeIn().delay(3000).fadeOut("slow").slideUp("slow");
</script>   

(Above is untested, meant only for illustration.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM