Ajax.BeginForm OnSuccess,onBegin,OnFailure没有触发

时间:2018-02-23 09:01:35

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

无论我尝试什么,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。没有事件被解雇。有什么想法吗?

1 个答案:

答案 0 :(得分: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" }))