Ajax.BiginForm 导致回发。我有两个 Ajax 脚本,也没有嵌套表单

发布于 2024-11-28 06:16:40 字数 11993 浏览 0 评论 0原文

我正在尝试使用 Ajax.BefinForm(),并尝试了网上可用的所有方法以避免发回帖子。我只是不明白我做错了什么。请帮我解决这个问题。

主视图:

@model GenericApp.Models.ExperienceModel
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"    type="text/javascript"></script>
@{
    ViewBag.Title = "Details";
    var comments = Model.Comments == null ? new GenericApp.Models.Comments() :    Model.Comments;

    //comments.
}
<h2>Details</h2>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>
<fieldset>
    <legend>ExperienceModel</legend>
    <div class="display-field">
        <h2>
            @Html.DisplayFor(model => model.Title)
        </h2>
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Description)
    </div>
    <div class="display-field">
         <b>Created By:</b> @Html.DisplayFor(model => model.CreatedBy)
    </div>
    <div class="display-field">
        <b>Create Date:</b> @Html.DisplayFor(model => model.CreateDate)
    </div>
    <div class="display-field">
        <b>Modified By:</b> @Html.DisplayFor(model => model.ModifiedBy)
    </div>
    <div class="display-field">
        <b>Modified Date:</b> @Html.DisplayFor(model => model.ModifiedDate)
    </div>
 </fieldset>
 @if (User.Identity.Name == null || User.Identity.Name.Length == 0)
 {
    <div>To view or add comments, please log-in</div>
 }
else
{
    <div id="ShowAllComments">
        @Html.Partial("_ShowComments", comments)
    </div>
}

部分视图“_ShowComments”

@model GenericApp.Models.Comments
<table>
    <tr>
        <th>
            Description
        </th>
        <th>
            CreatedBy
        </th>
        <th>
            CreateDate
        </th>
    </tr>
    @foreach (var item in Model.CommentList)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CreatedBy)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CreateDate)
            </td>
        </tr>

    }
</table>
@{
    GenericApp.Models.Comment comment = new GenericApp.Models.Comment();
    AjaxOptions opts = new AjaxOptions()
    {
        UpdateTargetId = "ShowAllComments",
        HttpMethod = "POST",
        Confirm = "Are you sure you want to save your comments",
        InsertionMode = InsertionMode.Replace
    };
    using (Ajax.BeginForm("StoreComments", new { id = Model.ParentID}, opts, new { id = "ajaxForm" }))
    {
        Html.ValidationSummary(true);
        <fieldset>
            <div class="editor-field">
                @Html.LabelFor(model => comment.Description)</div>
            <div class="editor-field">
                @Html.EditorFor(model => comment.Description)
                @Html.ValidationMessageFor(model => comment.Description)
            </div>
        </fieldset>
        <input type="submit" value="Save" />
    }
}

控制器中的操作代码:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult StoreComments(int id, FormCollection collection)
    {
        if (Request.IsAjaxRequest())
        {
            ExperienceModel exp = getExpById(id);
            if (exp.Comments == null)
            {
                exp.Comments = new Comments();
                exp.Comments.ParentID = exp.ID;
                exp.Comments.CommentList = new List<Comment>();
            }
            Comment com = new Comment();
            com.Description = Request.Params["comment.Description"];
            com.CreatedBy = User.Identity.Name;
            com.CreateDate = new DateTime().ToString();
            com.ID = exp.Comments.CommentList.Count;
            exp.Comments.CommentList.Add(com);
            return PartialView("_ShowComments", exp.Comments);
        }
        else
        {
            return this.Content("Hi");
        }
    }

我总是在空白页面中看到“Hi”

渲染的 HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Details</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                    Welcome <strong>sadanands</strong>!
    [ <a href="/Account/LogOff">Log Off</a> ]

            </div>
            <div id="menucontainer">
                <ul id="menu">
                    <li><a href="/">Home</a></li>
                    <li><a href="/Home/About">About Us</a></li>
                    <li><a href="/Experience">Our Experience</a></li>
                    <li></li>
                </ul>
            </div>
        </div>
        <div id="main">
            <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"     type="text/javascript"></script>
<h2>Details</h2>
<p>
    <a href="/Experience/Edit/1">Edit</a> |
    <a href="/Experience">Back to List</a>
</p>
<fieldset>
    <legend>ExperienceModel</legend>
    <div class="display-field">
        <h2>
            First Exp
        </h2>
    </div>
    <div class="display-field">
        hsdh asfhasjfkl fidsjfkldsj fkl dklds lfjdslfj sdsfhkjhdsf ahdfklhs fdsfhklds fldshfklsd fdskfhklds fkjds fhdskfhs fds fkfhkjds ffhsdk
    </div>
    <div class="display-field">
        <b>Created By:</b> xxxxxxx
    </div>
    <div class="display-field">
        <b>Create Date:</b> 1/1/2010
    </div>
    <div class="display-field">
        <b>Modified By:</b> abcdefg
    </div>
    <div class="display-field">
        <b>Modified Date:</b> 1/5/2010
    </div>
</fieldset>
    <div id="ShowAllComments">
        <table>
    <tr>
        <th>
            Description
        </th>
        <th>
            CreatedBy
        </th>
        <th>
            CreateDate
        </th>
    </tr>
</table>
<form action="/Experience/StoreComments/0" data-ajax="true" data-ajax-confirm="Are you sure you want to save your comments" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#ShowAllComments" id="ajaxForm" method="post">        <fieldset>
            <div class="editor-field">
                <label for="comment_Description">Description</label></div>
            <div class="editor-field">
                <textarea class="text-box multi-line" data-val="true" data-val-required="The Description field is required." id="comment_Description" name="comment.Description">
</textarea>
                <span class="field-validation-valid" data-valmsg-for="comment.Description" data-valmsg-replace="true"></span>
            </div>
        </fieldset>
        <input type="submit" value="Save" />
</form>
    </div>


        </div>
        <div id="footer">
        </div>
    </div>
</body>
</html>

我在页面上没有看到任何 javascript 错误。我确实使用 IE 调试器工具来检查 MicrosoftAjax.js 和 MicrosoftMvcAjax.js 是否已加载,它们确实加载了。

任何帮助都将非常感谢

视图文件夹中的 My Web.Config:

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor"     type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral,     PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="GenericApp.Infrastructure" />
        <add namespace="GenericApp.Extensions"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
    Enabling request validation in view pages would cause validation to occur
    after the input has already been processed by the controller. By default
    MVC performs request validation before a controller processes the input.
    To change this behavior apply the ValidateInputAttribute to a
    controller or action.
-->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode"     type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

希望我已将所有信息放在这里。

I am trying to use Ajax.BefinForm(), and have tried everything available on net to avoid getting a post back. I just cannot figure out what i have done wrong. Please help me with this.

Main View:

@model GenericApp.Models.ExperienceModel
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"    type="text/javascript"></script>
@{
    ViewBag.Title = "Details";
    var comments = Model.Comments == null ? new GenericApp.Models.Comments() :    Model.Comments;

    //comments.
}
<h2>Details</h2>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>
<fieldset>
    <legend>ExperienceModel</legend>
    <div class="display-field">
        <h2>
            @Html.DisplayFor(model => model.Title)
        </h2>
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Description)
    </div>
    <div class="display-field">
         <b>Created By:</b> @Html.DisplayFor(model => model.CreatedBy)
    </div>
    <div class="display-field">
        <b>Create Date:</b> @Html.DisplayFor(model => model.CreateDate)
    </div>
    <div class="display-field">
        <b>Modified By:</b> @Html.DisplayFor(model => model.ModifiedBy)
    </div>
    <div class="display-field">
        <b>Modified Date:</b> @Html.DisplayFor(model => model.ModifiedDate)
    </div>
 </fieldset>
 @if (User.Identity.Name == null || User.Identity.Name.Length == 0)
 {
    <div>To view or add comments, please log-in</div>
 }
else
{
    <div id="ShowAllComments">
        @Html.Partial("_ShowComments", comments)
    </div>
}

Partial View "_ShowComments"

@model GenericApp.Models.Comments
<table>
    <tr>
        <th>
            Description
        </th>
        <th>
            CreatedBy
        </th>
        <th>
            CreateDate
        </th>
    </tr>
    @foreach (var item in Model.CommentList)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CreatedBy)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CreateDate)
            </td>
        </tr>

    }
</table>
@{
    GenericApp.Models.Comment comment = new GenericApp.Models.Comment();
    AjaxOptions opts = new AjaxOptions()
    {
        UpdateTargetId = "ShowAllComments",
        HttpMethod = "POST",
        Confirm = "Are you sure you want to save your comments",
        InsertionMode = InsertionMode.Replace
    };
    using (Ajax.BeginForm("StoreComments", new { id = Model.ParentID}, opts, new { id = "ajaxForm" }))
    {
        Html.ValidationSummary(true);
        <fieldset>
            <div class="editor-field">
                @Html.LabelFor(model => comment.Description)</div>
            <div class="editor-field">
                @Html.EditorFor(model => comment.Description)
                @Html.ValidationMessageFor(model => comment.Description)
            </div>
        </fieldset>
        <input type="submit" value="Save" />
    }
}

Action Code in my controller:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult StoreComments(int id, FormCollection collection)
    {
        if (Request.IsAjaxRequest())
        {
            ExperienceModel exp = getExpById(id);
            if (exp.Comments == null)
            {
                exp.Comments = new Comments();
                exp.Comments.ParentID = exp.ID;
                exp.Comments.CommentList = new List<Comment>();
            }
            Comment com = new Comment();
            com.Description = Request.Params["comment.Description"];
            com.CreatedBy = User.Identity.Name;
            com.CreateDate = new DateTime().ToString();
            com.ID = exp.Comments.CommentList.Count;
            exp.Comments.CommentList.Add(com);
            return PartialView("_ShowComments", exp.Comments);
        }
        else
        {
            return this.Content("Hi");
        }
    }

I alway end up seeing "Hi" in a blank page

Rendered HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Details</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                    Welcome <strong>sadanands</strong>!
    [ <a href="/Account/LogOff">Log Off</a> ]

            </div>
            <div id="menucontainer">
                <ul id="menu">
                    <li><a href="/">Home</a></li>
                    <li><a href="/Home/About">About Us</a></li>
                    <li><a href="/Experience">Our Experience</a></li>
                    <li></li>
                </ul>
            </div>
        </div>
        <div id="main">
            <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"     type="text/javascript"></script>
<h2>Details</h2>
<p>
    <a href="/Experience/Edit/1">Edit</a> |
    <a href="/Experience">Back to List</a>
</p>
<fieldset>
    <legend>ExperienceModel</legend>
    <div class="display-field">
        <h2>
            First Exp
        </h2>
    </div>
    <div class="display-field">
        hsdh asfhasjfkl fidsjfkldsj fkl dklds lfjdslfj sdsfhkjhdsf ahdfklhs fdsfhklds fldshfklsd fdskfhklds fkjds fhdskfhs fds fkfhkjds ffhsdk
    </div>
    <div class="display-field">
        <b>Created By:</b> xxxxxxx
    </div>
    <div class="display-field">
        <b>Create Date:</b> 1/1/2010
    </div>
    <div class="display-field">
        <b>Modified By:</b> abcdefg
    </div>
    <div class="display-field">
        <b>Modified Date:</b> 1/5/2010
    </div>
</fieldset>
    <div id="ShowAllComments">
        <table>
    <tr>
        <th>
            Description
        </th>
        <th>
            CreatedBy
        </th>
        <th>
            CreateDate
        </th>
    </tr>
</table>
<form action="/Experience/StoreComments/0" data-ajax="true" data-ajax-confirm="Are you sure you want to save your comments" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#ShowAllComments" id="ajaxForm" method="post">        <fieldset>
            <div class="editor-field">
                <label for="comment_Description">Description</label></div>
            <div class="editor-field">
                <textarea class="text-box multi-line" data-val="true" data-val-required="The Description field is required." id="comment_Description" name="comment.Description">
</textarea>
                <span class="field-validation-valid" data-valmsg-for="comment.Description" data-valmsg-replace="true"></span>
            </div>
        </fieldset>
        <input type="submit" value="Save" />
</form>
    </div>


        </div>
        <div id="footer">
        </div>
    </div>
</body>
</html>

I dont see any javascript error on the page. I did use the IE debugger tool to check if MicrosoftAjax.js and MicrosoftMvcAjax.js are getting loaded, and they do.

Any help would be highly appriciated

My Web.Config in Views Folder:

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor"     type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral,     PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="GenericApp.Infrastructure" />
        <add namespace="GenericApp.Extensions"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
    Enabling request validation in view pages would cause validation to occur
    after the input has already been processed by the controller. By default
    MVC performs request validation before a controller processes the input.
    To change this behavior apply the ValidateInputAttribute to a
    controller or action.
-->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode"     type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

Hope i have put all the information out here.

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

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

发布评论

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

评论(1

霓裳挽歌倾城醉 2024-12-05 06:16:40

我已经找到答案了。

在视图中,我包含了所有必要的脚本,除了一个脚本,

如果您查看我之前帖子中的主视图,它有,

<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"      type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"    type="text/javascript"></script>

但缺少一个脚本:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

添加了此脚本标记后,我想您可以取消 MicrosoftAjax.js 和 MicrosoftMvcAjax。 js 并且代码仍然应该可以工作。它对我有用。

萨达南德

I have figured out the answer.

In the view i included all the necessary scripts except for one

if you look at the main view in my earlier post it has

<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"      type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"    type="text/javascript"></script>

but the missing one was:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

having added this script tag, i guess you can do away with MicrosoftAjax.js and MicrosoftMvcAjax.js and still the code should work. It did for me.

Sadanand

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