对 ActionResult 进行 jQuery ajax 调用时页面会刷新

发布于 2024-07-27 19:29:09 字数 6149 浏览 4 评论 0原文

当我在示例中添加评论时,我的页面会刷新。 我做错了什么?

我希望在不刷新页面的情况下更新详细信息页面中的评论。
我正在尝试做一些与 StackOverflow 上添加评论的方式非常相似的事情。
我的 Details.aspx 有一个问题列表,单击后会转到详细信息/id 页面,其中显示该问题的所有评论。 评论是通过部分视图加载的。 详细信息页面上有一个表单,它调用 ActionResult 方法 (AddComment) 将评论添加到数据库并返回部分视图。

数据库

CREATE TABLE [dbo].[Comment](
[CommentId] [int] IDENTITY(1,1) NOT NULL,
[IssueId] [int] NOT NULL,
[Comment] [varchar](50) NULL,
CONSTRAINT [PK_Comment] PRIMARY KEY CLUSTERED 
(
[CommentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Issue](
[IssueId] [int] IDENTITY(1,1) NOT NULL,
[Title] [varchar](50) NULL,
CONSTRAINT [PK_Issue] PRIMARY KEY CLUSTERED 
(
[IssueId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Index.aspx

    <p><ul>
<% foreach (var item in (IEnumerable<PartialUpdates.Models.Issue>)Model)
   { %>
<li>

<a href="<%= Url.RouteUrl("Default",  new { id = item.IssueId, controller = "Home", action = "Details" })%>"><%= item.Title%></a> 
</li>
 <% } %>
 </ul> </p>

Details.aspx

<fieldset>
    <legend>Fields</legend>
    <p>
        IssueId:
        <%= Html.Encode(Model.Issue.IssueId) %>
    </p>
    <p>
        Title:
        <%= Html.Encode(Model.Issue.Title) %>
    </p>
    <div id="issueComments">
    <% Html.RenderPartial("Comments", Model.Comments); %>
    </div>

    <div id="issue-comment-form">
<form id="form-comments-<%= Html.Encode(Model.Issue.IssueId) %>" class="post-comments">
<table><tr><td><textarea class="wmd-ignore" name="comment" cols="68" rows="3" id="form-comment-<%= Html.Encode(Model.Issue.IssueId) %>"></textarea>
<input type="submit" value="Add Comment" /></td></tr><tr><td><span class="text-counter"></span>
<span class="form-error"></span></td></tr></table>
</form></div>

</fieldset>
<script type="text/javascript">
$(document).ready(function() {
    $("#form-comments-<%= Html.Encode(Model.Issue.IssueId) %>").submit(function(evt) {            
        var frm = $("#form-comments-<%= Html.Encode(Model.Issue.IssueId) %>");
        var action = frm.attr("action");
        var serializedForm = frm.serialize();
        var comments = jQuery.trim($("#form-comment-<%= Html.Encode(Model.Issue.IssueId) %>").val());
        if (comments.length < 1)
            return;
        AjaxPostComment("<%= Html.Encode(Model.Issue.IssueId) %>", comments);

    });
});
function AjaxPostComment(issueId, comments) {
    $.ajax({
        type: "POST",
        url: "/Home/" + "AddComment",
        dataType: "html",
        data: {
            comment: comments,
            id: issueId
        },
        success: function(v) {
            RefreshComment(v);

        },
        error: function(v, x, w) {
            //Error
            alert('error: ' + v);
            alert('error: ' + x);
            alert('error: ' + w);
            return false;
        }
    });
}
function RefreshComment(v) {

    $("div#issueComments").html(v);
    return false;
    if (v == "true") {
        $("#issueComments").load("CommentHistory");
        //$("div#issueComments").html(v);// does this work?
    }
    else {
    }
}
</script>

IssuePageViewModel

public class IssuePageViewModel
{
    public IEnumerable<Issue> Issues { get; private set; }
    public IEnumerable<Comment> Comments { get; private set; }
    public Issue Issue { get; private set; }

    public IssuePageViewModel(Issue issue, IEnumerable<Comment> issueComments)
    {
        this.Issue = issue;
        this.Comments = issueComments;
    }
}

HomeController.cs

        MyMVCSamplesDBEntities _db;

    public HomeController()
    {
        _db = new MyMVCSamplesDBEntities();
    }

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        ViewData.Model = (from i in _db.Issue select i).ToList();

        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Details(int? id)
    {
        Issue issue = _db.Issue.First(i => i.IssueId == id);
        var comments = _db.Comment.Where(x => x.IssueId == id).ToList();
        IssuePageViewModel viewData = new IssuePageViewModel(issue, comments);

        return View(viewData);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult AddComment(int id, string comment)
    {
        Comment com = new Comment();
        com.Comment1 = comment;
        com.CommentId = id;
        com.IssueId = id;
        _db.AddToComment(com);
        _db.SaveChanges(true);

        var comments = _db.Comment.Where(x => x.IssueId == id).ToList();
        ViewData["NewComments"] = comments;
        if (Request.IsAjaxRequest())
        {
            return PartialView("Comments", ViewData["NewComments"]);
        }
        else
        {
            return View();
        }
    }

Master

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
</head>

My page is refreshing when I add a Comment in my example. What am I doing wrong?

I want the comments in the Details page to update without refreshing the page.
I am trying to do something very similar to how the comments are added here on StackOverflow.
My Details.aspx has a list of Issues, when clicked goes to a Details/id page which shows all the Comments of the Issue. Comments are loaded via a partialview. There is a form on the details page which calls a ActionResult method (AddComment) to add the comment to the database and returns a partial view.

Database

CREATE TABLE [dbo].[Comment](
[CommentId] [int] IDENTITY(1,1) NOT NULL,
[IssueId] [int] NOT NULL,
[Comment] [varchar](50) NULL,
CONSTRAINT [PK_Comment] PRIMARY KEY CLUSTERED 
(
[CommentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Issue](
[IssueId] [int] IDENTITY(1,1) NOT NULL,
[Title] [varchar](50) NULL,
CONSTRAINT [PK_Issue] PRIMARY KEY CLUSTERED 
(
[IssueId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Index.aspx

    <p><ul>
<% foreach (var item in (IEnumerable<PartialUpdates.Models.Issue>)Model)
   { %>
<li>

<a href="<%= Url.RouteUrl("Default",  new { id = item.IssueId, controller = "Home", action = "Details" })%>"><%= item.Title%></a> 
</li>
 <% } %>
 </ul> </p>

Details.aspx

<fieldset>
    <legend>Fields</legend>
    <p>
        IssueId:
        <%= Html.Encode(Model.Issue.IssueId) %>
    </p>
    <p>
        Title:
        <%= Html.Encode(Model.Issue.Title) %>
    </p>
    <div id="issueComments">
    <% Html.RenderPartial("Comments", Model.Comments); %>
    </div>

    <div id="issue-comment-form">
<form id="form-comments-<%= Html.Encode(Model.Issue.IssueId) %>" class="post-comments">
<table><tr><td><textarea class="wmd-ignore" name="comment" cols="68" rows="3" id="form-comment-<%= Html.Encode(Model.Issue.IssueId) %>"></textarea>
<input type="submit" value="Add Comment" /></td></tr><tr><td><span class="text-counter"></span>
<span class="form-error"></span></td></tr></table>
</form></div>

</fieldset>
<script type="text/javascript">
$(document).ready(function() {
    $("#form-comments-<%= Html.Encode(Model.Issue.IssueId) %>").submit(function(evt) {            
        var frm = $("#form-comments-<%= Html.Encode(Model.Issue.IssueId) %>");
        var action = frm.attr("action");
        var serializedForm = frm.serialize();
        var comments = jQuery.trim($("#form-comment-<%= Html.Encode(Model.Issue.IssueId) %>").val());
        if (comments.length < 1)
            return;
        AjaxPostComment("<%= Html.Encode(Model.Issue.IssueId) %>", comments);

    });
});
function AjaxPostComment(issueId, comments) {
    $.ajax({
        type: "POST",
        url: "/Home/" + "AddComment",
        dataType: "html",
        data: {
            comment: comments,
            id: issueId
        },
        success: function(v) {
            RefreshComment(v);

        },
        error: function(v, x, w) {
            //Error
            alert('error: ' + v);
            alert('error: ' + x);
            alert('error: ' + w);
            return false;
        }
    });
}
function RefreshComment(v) {

    $("div#issueComments").html(v);
    return false;
    if (v == "true") {
        $("#issueComments").load("CommentHistory");
        //$("div#issueComments").html(v);// does this work?
    }
    else {
    }
}
</script>

IssuePageViewModel

public class IssuePageViewModel
{
    public IEnumerable<Issue> Issues { get; private set; }
    public IEnumerable<Comment> Comments { get; private set; }
    public Issue Issue { get; private set; }

    public IssuePageViewModel(Issue issue, IEnumerable<Comment> issueComments)
    {
        this.Issue = issue;
        this.Comments = issueComments;
    }
}

HomeController.cs

        MyMVCSamplesDBEntities _db;

    public HomeController()
    {
        _db = new MyMVCSamplesDBEntities();
    }

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        ViewData.Model = (from i in _db.Issue select i).ToList();

        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Details(int? id)
    {
        Issue issue = _db.Issue.First(i => i.IssueId == id);
        var comments = _db.Comment.Where(x => x.IssueId == id).ToList();
        IssuePageViewModel viewData = new IssuePageViewModel(issue, comments);

        return View(viewData);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult AddComment(int id, string comment)
    {
        Comment com = new Comment();
        com.Comment1 = comment;
        com.CommentId = id;
        com.IssueId = id;
        _db.AddToComment(com);
        _db.SaveChanges(true);

        var comments = _db.Comment.Where(x => x.IssueId == id).ToList();
        ViewData["NewComments"] = comments;
        if (Request.IsAjaxRequest())
        {
            return PartialView("Comments", ViewData["NewComments"]);
        }
        else
        {
            return View();
        }
    }

Master

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
</head>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

风蛊 2024-08-03 19:29:09

详细信息页面上有一个表单,它调用 ActionResult 方法 (AddComment) 将评论添加到数据库并返回部分视图。 您的 jQuery 表单 submit() 方法不会阻止实际提交的发生。 您需要在该函数中的某个位置执行 evt.preventDefault();

There is a form on the details page which calls a ActionResult method (AddComment) to add the comment to the database and returns a partial view. Your jQuery form submit() method doesn't prevent the actual submission from taking place. You need to do evt.preventDefault(); somewhere in that function.

‘画卷フ 2024-08-03 19:29:09

您的 jQuery 表单 commit() 方法不会阻止实际提交的发生。 您需要在该函数中的某个位置执行 evt.preventDefault();

Your jQuery form submit() method doesn't prevent the actual submission from taking place. You need to do evt.preventDefault(); somewhere in that function.

剩一世无双 2024-08-03 19:29:09

我可能会对此投反对票,而且我什至没有阅读过您的任何代码,但 99% 的情况下,“页面刷新”和“Javascript”往往指向事件处理程序中的 Javascript 语法错误(例如,在本例中为submit),或者无法阻止事件的默认操作。

I'll probably take some downvotes for this, and I haven't even read through any of your code, but 99% of the time, "page refreshes" and "Javascript" tends to point to a Javascript syntax error in an event handler (eg in this case submit), or a failure to prevent the default action of an event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文