如何防止Ajax重定向到Asp.net Mvc 5中的另一个页面

时间:2022-11-09 03:31:11

I have two forms in a single page.One of them is for adding comment, the other one is the main blog content as follows.

我在一页纸上有两张表格。其中一个是添加评论,另一个是主要的博客内容如下。

My aim is to have blog page with adding comment functionality.When user adds a comment , I want to post the comment another controller using ajax.When providing this functionality,I want user stay at the same page and update comments partial view at the page.However I couldn't achieve this with the codes below.

我的目标是有博客页面添加评论功能。当用户添加注释时,我希望使用ajax发布另一个控制器的注释。当提供此功能时,我希望用户停留在相同的页面上并更新页面上的评论部分视图。但是我不能用下面的代码来实现。

Main Blog Content

主要的博客内容

@model WforViolation.Models.Violation

@{
    ViewBag.Title = "Details";
}


<h1>@Model.Title</h1>
<p class="lead">
    Posted by @Model.CreatorUser.UserName<a href="#"></a>
</p>
<hr>
<!-- Date/Time -->
<p><span class="glyphicon glyphicon-time"></span> Posted on @Model.CreationDateTime <span class="glyphicon glyphicon-flag"></span> @Model.Severity Severity <span class="glyphicon glyphicon-comment"> </span> @Model.Comments.Count Comments </p>
<p><span class="glyphicon glyphicon-eye-open"> People Viewed</span></p>
<hr>
<!-- Preview Image -->
<img class="img-responsive" src="@Model.Picture.FirstOrDefault().MediumPath" alt="">
<hr>
<!-- Post Content -->
<p class="lead">@Model.Title</p>
<p>@Model.Description</p>

<hr>
<!-- Blog Comments -->
<!-- Comments Form -->
@Html.Partial("_AddComment", new WforViolation.Models.CommentViewModel() { ViolationId=Model.Id,Content=""})
<hr>
<!-- Posted Comments -->
<!-- Comment -->
@Html.Partial("_Comments",Model)

Add Comment View

添加评论视图

@model WforViolation.Models.CommentViewModel
<div class="well">
    <h4>Leave a Comment:</h4>

    @using (Ajax.BeginForm("AddComment", "Comment", null, new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "SuccessMessage",
        OnFailure = "FailMessage"
        //UpdateTargetId = "resultTarget"
    }, new { id = "MyNewNameId", role = "form" })) // set new Id name for  Form
    {
        @Html.AntiForgeryToken()
        <div class="form-group">
            @Html.TextAreaFor(model => model.Content, new { @rows = 3 })
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
        @Html.HiddenFor(model=>model.ViolationId)
    }
    </div>
<script>
    //\\\\\\\ JS  retrun message SucccessPost or FailPost
    function SuccessMessage() {
        alert("Succcess Post");
    }
    function FailMessage() {
        alert("Fail Post");
    }
</script>

My Comment Controller

我的评论控制器

  [HttpPost]
    public ActionResult AddComment(CommentViewModel commentViewModel)
    {
         Comment comment = new Comment();
         var userID = User.Identity.GetUserId();

        if (!string.IsNullOrEmpty(userID))
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var currentUser = manager.FindById(User.Identity.GetUserId());
            comment.ApplicationUser=currentUser;
        }
        var violationId = commentViewModel.ViolationId;
        Violation violationCommentedOn = context.Violations.Where(x => x.Id == violationId).FirstOrDefault();
        comment.Violation = violationCommentedOn;
        context.Comments.Add(comment);
        context.SaveChanges();
        var result = Json(
                       new
                       {
                           Success = true,//success
                           StatusMessage = "Object created successfully"
                       });
        return result;
    }

When I added a comment it redirects me to another page called localhost/Comment/AddComment its content is just the Json. Is it ever possible to just retrieve JsonResult and stay at the same page ?

当我添加一个注释时,它会将我重定向到另一个名为localhost/ comment /AddComment的页面,它的内容就是Json。是否可以只检索JsonResult并停留在同一页面?

Or I cant post a form data using ajax and not redirecting to another page?

或者我不能使用ajax发布表单数据而不重定向到另一个页面?

I know there are similar questions but I couldn't find the exact answer. Any help is appreciated.

我知道有类似的问题,但我找不到确切的答案。任何帮助都是感激。

1 个解决方案

#1


1  

You are using Form in your Add Comment view and that form calls AddComment in your controller that returns a json data. Forms do cause a redirect to the method they call and because your controller is returning json, the browser simply displays it on a new page.

在AddComment视图中使用表单,该表单在控制器中调用AddComment,返回json数据。表单确实会导致重定向到它们调用的方法,而且由于您的控制器返回json,浏览器只会在一个新页面上显示它。

You may either return a view from your AddComment method in the controller. This view could be the comment view. This way the control will redirect back to the same view with new data. This is a sample code, in practice, this code should be pretty much the same as you may have it in ShowAddCommentView method of the controller.

您可以在控制器中从AddComment方法返回一个视图。这个视图可以是评论视图。这样,控件将重定向到具有新数据的相同视图。这是一个示例代码,实际上,该代码应该与您在控制器的ShowAddCommentView方法中看到的代码差不多。

CommentViewModel commentVM; 
/// populate commentVM from DB or comment store
/// remove return result;
return View("AddCommentView", commentVM);  /// your add comment view name

Or instead of using Form to send data to the controller, use a simple ajax call without using AjaxForm. When a user clicks on the button, you can call Ajax in javascript. I have a jquery example. parameter1, parameter2 are the same as properties of your CommentViewModel. Of course, you can also use json data parameter in this call instead passing parameters like in this following sample.

或者不用表单向控制器发送数据,而是使用简单的ajax调用,而不用AjaxForm。当用户单击按钮时,可以使用javascript调用Ajax。我有一个jquery示例。parameter1、parameter2与CommentViewModel的属性相同。当然,您也可以在这个调用中使用json数据参数,而不是像下面这个示例那样传递参数。

$.ajax({
        url: '/Comment/AddComment?parameter1='+ pvalue1 + '&parameter2=' + pvalue2,
        async: false,
        cache: false,
        type: 'POST',
        success: function (msg) {
            /// this msg object is actually the json object your controller is returning. 
        }
    });

This call will not cause the page to redirect. When json is returned, you may write code in javascript to do something with that data, perhaps display it back on the add comment page.

此调用不会导致页面重定向。当返回json时,您可以使用javascript编写代码来处理该数据,或者将其显示回add comment页面。

It is possible to make this ajax call from asp.net directly without using a separate javascript. But I can't seem to remember it exactly right now.

不使用单独的javascript就可以直接从asp.net进行ajax调用。但我现在似乎记不太清了。

#1


1  

You are using Form in your Add Comment view and that form calls AddComment in your controller that returns a json data. Forms do cause a redirect to the method they call and because your controller is returning json, the browser simply displays it on a new page.

在AddComment视图中使用表单,该表单在控制器中调用AddComment,返回json数据。表单确实会导致重定向到它们调用的方法,而且由于您的控制器返回json,浏览器只会在一个新页面上显示它。

You may either return a view from your AddComment method in the controller. This view could be the comment view. This way the control will redirect back to the same view with new data. This is a sample code, in practice, this code should be pretty much the same as you may have it in ShowAddCommentView method of the controller.

您可以在控制器中从AddComment方法返回一个视图。这个视图可以是评论视图。这样,控件将重定向到具有新数据的相同视图。这是一个示例代码,实际上,该代码应该与您在控制器的ShowAddCommentView方法中看到的代码差不多。

CommentViewModel commentVM; 
/// populate commentVM from DB or comment store
/// remove return result;
return View("AddCommentView", commentVM);  /// your add comment view name

Or instead of using Form to send data to the controller, use a simple ajax call without using AjaxForm. When a user clicks on the button, you can call Ajax in javascript. I have a jquery example. parameter1, parameter2 are the same as properties of your CommentViewModel. Of course, you can also use json data parameter in this call instead passing parameters like in this following sample.

或者不用表单向控制器发送数据,而是使用简单的ajax调用,而不用AjaxForm。当用户单击按钮时,可以使用javascript调用Ajax。我有一个jquery示例。parameter1、parameter2与CommentViewModel的属性相同。当然,您也可以在这个调用中使用json数据参数,而不是像下面这个示例那样传递参数。

$.ajax({
        url: '/Comment/AddComment?parameter1='+ pvalue1 + '&parameter2=' + pvalue2,
        async: false,
        cache: false,
        type: 'POST',
        success: function (msg) {
            /// this msg object is actually the json object your controller is returning. 
        }
    });

This call will not cause the page to redirect. When json is returned, you may write code in javascript to do something with that data, perhaps display it back on the add comment page.

此调用不会导致页面重定向。当返回json时,您可以使用javascript编写代码来处理该数据,或者将其显示回add comment页面。

It is possible to make this ajax call from asp.net directly without using a separate javascript. But I can't seem to remember it exactly right now.

不使用单独的javascript就可以直接从asp.net进行ajax调用。但我现在似乎记不太清了。