【问题标题】:Ajax.BeginForm OnSuccess, onBegin , OnFailure not firingAjax.BeginForm OnSuccess、onBegin、OnFailure 未触发
【发布时间】:2018-08-03 07:17:19
【问题描述】:

无论我尝试什么,所有 javascript 方法都不会触发/工作。

[HttpPost]
public JsonResult Errors (string name, string email)
{
    //send email
        return new JsonResult()
        {
            Data = new { result = "success" },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
}

局部视图

@using (Ajax.BeginForm(
    "Errors", 
    "Home", 
    new AjaxOptions { 
        HttpMethod = "POST", 
        OnSuccess = "onSuccess ", 
        OnFailure = "OnFailure", 
        OnBegin = "Begin()" }, 
    new { @class = "form-horizontal",  id = "error-form" }))
{
        @Html.AntiForgeryToken()

        <div class="form-group">
          <label>Your name</label>
          <input type="text" name="name" class="form-control" value="@name" />
        </div>
        <div class="form-group">
          <label>Your e-mail</label>
          <input type="text" name="email" class="form-control" value="@email" />
        </div>



        <button class="btn btn-success" type="submit" style="margin-bottom:4em;">Send message</button>
      }

      <div class="form-group" id="thankYou" style="display:none">
        <label>Thank you!</label>
      </div>

    </div>
  </div>
</div>

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
  function Begin() {
    alert("b");
  }

  function onSuccess(data) {
    debugger;
    alert(data.result);
  };

  function OnFailure(data) {
    debugger;
    alert(data.result);
  };

  $(document).ready(function () {

  });

</script>

我得到的只是 JSON 格式的响应。见screenshot。没有事件被触发。有什么想法吗?

【问题讨论】:

  • 这是剃刀语法吗?请添加该标签。如果您格式化代码,那么您可能会更幸运地获得回复,这样人们根本不必向右滚动,尤其是看到代码中最重要的部分;并删除所有额外的东西——样式、类、脚本、空行——只包括重现问题所绝对必要的内容。

标签: javascript asp.net ajax asp.net-ajax


【解决方案1】:

Ajax.BeginForm 有 11 个重载...您的参数与其中任何一个都不匹配。我假设你想使用this overload:

BeginForm(AjaxHelper, String, String, RouteValueDictionary, AjaxOptions, IDictionary<String,Object>)

您需要将RouteValueDictionary 添加到您的参数中:

@using (Ajax.BeginForm(
    "Errors",                     // <--action name
    "Home",                       // <--controller
    null,                         // <-- RouteValueDictionary
    new AjaxOptions {             // <-- AjaxOptions
        HttpMethod = "POST", 
        OnSuccess = "onSuccess ", 
        OnFailure = "OnFailure", 
        OnBegin = "Begin()" }, 
    new {                         // <-- htmlAttributes
        @class = "form-horizontal", 
        id = "error-form" }))

【讨论】:

    猜你喜欢
    • 2014-12-09
    • 2018-09-21
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    相关资源
    最近更新 更多