以编程方式将部分视图添加到MVC 5中的视图时出现JavaScript问题

时间:2018-01-16 13:56:13

标签: javascript razor asp.net-mvc-5

我正在关注教程:http://www.c-sharpcorner.com/article/comments-system-with-asp-net-mvc-5-and-jquery2/

我有一个MVC 5应用程序,其主视图在单击“注释”按钮或添加新注释时加载第一个局部视图。 JavaScript ajax调用返回第一个局部视图的action方法,然后动态构建第一个局部视图区域。现在,这个第一部分视图有一个"回复评论"单击链接时,JavaScript ajax调用返回另一个局部视图的action方法 - 第二个。问题是JavaScript第一次运行 - 在主视图中(单击“注释”按钮或单击“添加注释”按钮)但不是“链接时间”#34;回复评论"在第一个局部视图区域中单击。

为什么?

"回复评论的区域"链接是,是我添加评论回复帖子后加载的第一个局部视图。

enter image description here

对于一个简单的测试,我只是在第一个局部视图的JavaScript .ready函数中有一个警告。没有其他东西(通常它会加载第二个局部视图的ajax调用)。但是,它不会发射。

这是执行JavaScript ajax调用以加载第一个局部视图的主视图。它工作正常。它动态构建并显示html区域以保存第一个局部视图。



@model IQueryable<Comments.ViewModels.PostsVM>

@{
    ViewBag.Title = "GetPosts";
}

@if (Model != null)
{
    // Loop threw the model to display the posts.
    foreach (var post in Model)
    {
        <div class="panel panel-default" style="width: 80%;">
            @* Panel area. *@
            <div class="panel-body">
                <div class="avatar">
                    <img src="~/Images/avatar.png" class="img-circle" style="width: 60px;" />
                    @* Defaulting to a user to start the posts off. *@
                    <span> <a href="" style="font-weight:bold">Danny</a> </span><br />
                    <p style="margin-left: 60px; margin-top: -19px;">
                        <span class="glyphicon glyphicon-time" aria-hidden="true"></span>
                        <time class="timeago" datetime="@post.PostedDate">@post.PostedDate</time>
                    </p>
                </div>

                @* Post message area. *@
                <div class="postMessage" style="margin-top: 11px; margin-left: 9px;">
                    <span class="label label-warning"> @string.Format("Post #{0}", post.PostID) </span><br />
                    <p class="message">
                        @post.Message
                    </p>
                </div>
            </div>

            @* Panel area - to hold all the comment button. *@
            <div class="panel-footer">
                @* Button. *@
                <button type="button" class="btn btn-default Comment" data-id="@post.PostID" value="Comment">
                    <span class="glyphicon glyphicon-comment" aria-hidden="true"></span> Comment
                </button>
            </div>

            @* The area dynamically built. It will hold the partial view - Shared/_MyComments.cshtml. *@

            @* Add comment area. *@
            <div id="@string.Format("{0}_{1}","commentsBlock", post.PostID)" style="border: 1px solid #f1eaea; background-color: #eaf2ff;">
                <div class="AddComment" style="margin-left: 30%;  margin-bottom: 5px; margin-top: 8px;">
                    <input type="text" id="@string.Format("{0}_{1}", "comment", post.PostID)" class="form-control" placeholder="Add a Comment ..." style="display: inline;" />
                    @* Button. *@
                    <button type="button" class="btn btn-default addComment" data-id="@post.PostID"><span class="glyphicon glyphicon-comment" aria-hidden="true"></span></button>
                </div>
            </div>
        </div>
    }
}

<!-- Internal JavaScript. -->
@section Scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            // For when clicking the Comment button.
            $('.Comment').on('click', function () {
                var id = $(this).attr("data-id");

                var allCommentsArea = $('<div>').addClass('allComments_' + id);

                // Call the Comments controllers action method to get all the comments related to the post id. Will show a partial view.
                $.ajax({
                    type: 'GET',
                    url: '@Url.Action("GetComments", "Comments")',
                    data: { postId: id },
                    success: function (response) {
                        if ($('div').hasClass('allComments_' + id + ''))
                        {
                            // Remove.
                            $('div[class=allComments_' + id + ']').remove();
                        }

                        // For testing:
                        //console.log(response);

                        // Dynamically building the HTML to hold the comments returned. The area for the Shared/_MyComments.cshtml to be placed.
                        allCommentsArea.html(response);
                        allCommentsArea.prependTo('#commentsBlock_' + id);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Critical Error: something is wrong in the call to GetComments! Status: " + xhr.status + ". Error: " + thrownError.toString() + ". Response Text: " + xhr.responseText);
                    }
                })
            });

            // For when clicking the addComment button. Adding a new comment.
            $('.addComment').on('click', function () {
                var postId = $(this).attr('data-id');
                var commentMsg = $('#comment_' + postId).val();
                var dateTimeNow = new Date();

                // An object.
                var comment = {
                    CommentMsg: commentMsg,
                    CommentedDate: dateTimeNow.toLocaleString()
                };

                // Call the Comments controllers action method to get add a comment related to the post id. Will show a partial view.
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("AddComment", "Comments")',
                    data: { comment, postId },
                    success: function (response) {
                        $('div[class=allComments_' + postId + ']').remove();

                        // Dynamically building the HTML to hold the comments returned which now includes the added comment.
                        // The area for the Shared/_MyComments.cshtml to be placed.
                        var allCommentsArea = $('<div>').addClass('allComments_' + postId);

                        allCommentsArea.html(response);
                        allCommentsArea.prependTo('#commentsBlock_' + postId);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Critical Error: something is wrong in the call to AddComment! Status: " + xhr.status + ". Error: " + thrownError.toString() + ". Response Text: " + xhr.responseText);
                    }
                });
            });

            jQuery("time.timeago").timeago();
        });
    </script>
}
&#13;
&#13;
&#13;

这是第一个部分视图,其JavaScript不会触发:

&#13;
&#13;
@* A partial view called from the GetPosts.cshtml JavaScript function. *@
@* Has Internal Javascript.                                             *@

@* ---------------------------------------------------------------------------- *@
@* The @model - in this case the viewModel, contains the data needed here.      *@
@* ---------------------------------------------------------------------------- *@

@model IQueryable<Comments.ViewModels.CommentsVM>

@using Comments.ViewModels;

@if (Model != null)
{ 
    @* Loop threw the model to display the comments. *@
    foreach (CommentsVM comment in Model)
    {
        // A row.
        <div class="row" style="width: 100.3%; border-bottom: 1px solid #d2cece; margin-right: -14px; margin-left: -1px;">
            @* A column. *@
            <div class="col-md-4" style="width: 21%;">
                <div class="userProfil" style="margin-left: 9px; margin-top: 12px;">
                    <img src="~/Images/@comment.Users.ImageProfile" class="img-circle" style="width: 46px; height: 53px; border: 1px solid #bcb8b8;" />
                    <a href="#" style="margin-left: 5px; font-weight: bold; font-size: 13px;"> @comment.Users.UserName </a>
                </div>
            </div>

            @* A column. *@
            <div class="col-md-7" style="width: 60%;">
                <div class="commentDetails">
                    @* Area to hold the comment. *@
                    <p style="margin-top: 27px; font-size: 13px; color: #9c9898;"> @comment.CommentMsg </p>

                    <a href="#" class="Reply" data-id="@comment.CommentID">Reply To Comment</a>

                    <div class="@string.Format("{0}_{1}", "ReplayComments", comment.CommentID)" style="display:none;">
                        @* Area to add a sub comment. *@
                        <div class="ReplayCommentInput" style="margin-left: 3%;  margin-bottom: 5px; margin-top: 8px;">
                            <input type="text" id="@string.Format("{0}_{1}", "inputReplay", comment.CommentID)" class="form-control" placeholder="Add a Comment ..." style="display: inline;" />
                            <button type="button" class="btn btn-default ReplyAddComment" data-id="@comment.CommentID"><span class="glyphicon glyphicon-comment" aria-hidden="true"></span></button>
                        </div>
                    </div>
                </div>
            </div>

            @* A column. *@
            <div class="col-md-1" style="width: 19%;">
                <div class="commentDate">
                    <span class="glyphicon glyphicon-time" aria-hidden="true"></span>
                    <time class="timeago" style="margin-top: 27px; font-size: 13px; color: #9c9898;  margin-left: 4px;" datetime="@comment.CommentedDate">@comment.CommentedDate</time>
                </div>
            </div>
        </div>
    }
}

<script type="text/javascript">
     $(document).ready(function () {
        // For testing:
        alert("here I am");
     });
</script>
&#13;
&#13;
&#13;

现在当&#34;回复评论&#34;链接在第一部分被点击,它是激活一个JavaScript ajax调用来加载第二部分视图 - 我现在只是启动一个警报。这是JavaScript根本不会启动的时候。

0 个答案:

没有答案