开发者

Why is my jQuery.post() ajax failing when I return one View but does not fail when i return another?

开发者 https://www.devze.com 2023-01-31 19:55 出处:网络
I\'m trying to write a straightforward comment poster. I have this code in the controller: [HttpPost] [ValidateInput(false)]

I'm trying to write a straightforward comment poster. I have this code in the controller:

    [HttpPost]
    [ValidateInput(false)]
    public ViewResult Comments(MemberData md, long EntryId, string Comment, long LastId = 0)
    {
        bool isModerated = true;
        bool isLoggedIn = GenesisRepository.IsNotGuest(md.MemberGUID);
        bool isCommentAllowed = GenesisRepository.IsPermissionAssigned(md.MemberGUID, "Comments", "Create");

        // Moderate comment?
        if (moderateGuestComments == false && isLoggedIn == false开发者_StackOverflow社区) isModerated = false;
        if (moderateMemberComments == false && isLoggedIn) isModerated = false;

        long memberId = (from m in GenesisRepository.Member
                         where m.MemberGUID == md.MemberGUID
                         select m.MemberID)
                         .FirstOrDefault();

        if (
            EntryId > 0 
            && !string.IsNullOrEmpty(Comment) 
            && memberId > 0
            && isCommentAllowed)
        {
            Comments comment = new Comments { 
                Comment = Comment,
                Date = DateTime.Now,
                isActive = isModerated ? false : true,
                MemberID = memberId,
                StreamEntryID = EntryId,
            };
            if (GenesisRepository.SaveComment(comment))
            {
                List<Comments> comments = new List<Comments>();
                comments = (from c in GenesisRepository.Comments
                            where c.StreamEntryID == EntryId
                            && c.comID > LastId
                            select c
                            ).ToList();

                return View("DisplayComments", comments);
            }
        }

        return View("CommentError", "Unable to post comment.");
    }

When everything is fine and the action returns return View("DisplayComments", comments); the $.post() success function is triggered. But, When the action returns return View("CommentError", "Unable to post comment."); The $.post() ajax fails. I don't understand why the $.post() cares which view I'm returning.

Here's my Javascript:

<script type="text/javascript">
    $(document).ready(function () {

        $("#comments").ajaxError(function (event, request, settings) {
            alert("Error requesting page " + settings.url);
        });

        $("button#submitComment").click(function () {

            var commentList = $("#comments");

            var lastId = $(".comment h4").last().attr("id");
            var commentData = "EntryId=" + $("input#EntryID").val()
                                + "&Comment=" + $("textarea#Comment").val()
                                + "&LastId=" + lastId;

            $.post(
                "/find/Comments/Comments",
                commentData,
                function (data) {
                    alert("success");
                    alert(data);
                    if ($(data).filter(".error").length > 0) {
                        error = $(data);
                        $(this).after(error);
                    }
                    else {
                        newComments = $(data);
                        newComments.filter(".comment").css('display', 'none');
                        alert(newComments);
                        commentList.append(newComments);

                        $(".comment").each(function () {
                            $(this).slideDown("fast")
                        });

                        $("#Comment").attr("value", "");
                    }
                }
            );

        });
    });

</script>

What about this could cause the ajax to fail?

Here's what the two views look like:

View("DisplayComments", comments); (works)

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<Genesis.Domain.Entities.Comments>>" %>

<% foreach (var item in Model) %>
<% { %>
    <div class="comment" style="background:#eee; border:1px solid gray; padding:10px 10px 0 10px; margin-bottom:20px;">
        <h4 id="<%:item.comID %>"><%: item.Member.ScreenName%> commented on <%: String.Format("{0:f}", item.Date)%></h4>
        <p>
        <%: item.Comment%>
        </p>
    </div>
<% } %>

View("CommentError", "Unable to post comment."); (does not work)

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<div class="error">
<%:Model%>
</div>

What about this could cause the ajax post to fail?


If the ajaxError function is triggered this strongly indicates that your controller action returns a status code different than 200, probably 500 which is a strong indication that your controller action throws an exception before ever reaching the last line and be able to return a view.

So here are the steps to do:

  1. Use FireBug
  2. Look at what your server sends as response to the AJAX request
  3. Analyze the response status code and the response contents

Alternative approach:

  1. Put a breakpoint in your controller action
  2. Hit F5
  3. When the controller action is hit step through your code
  4. Observe exactly what happens

Remark: I would very strongly recommend you properly encoding your AJAX input. So instead of:

var commentData = "EntryId=" + $("input#EntryID").val()
                            + "&Comment=" + $("textarea#Comment").val()
                            + "&LastId=" + lastId;

you definitely should:

var commentData = $.param({
    EntryId: $("input#EntryID").val(),
    Comment: $("textarea#Comment").val(),
    LastId: lastId
});

Note that everytime you use the +, & and = signs when dealing with querystring parameters (no matter what language you are using) you are doing it wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消