MVC 5 Ajax.BeginForm Submit按钮调用当前页面而不是指定的Controller和Action的URL

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MVC 5 Ajax.BeginForm Submit按钮调用当前页面而不是指定的Controller和Action的URL相关的知识,希望对你有一定的参考价值。

我正在尝试使用Ajax.BeginForm,因此我可以将复选框的值传递给我的Controller Action。

我正在使用@ Ajax.ActionLink,但我无法获得新引入的复选框的值,所以我想继续使用Ajax.BeginForm。

由于@ Ajax.ActionLink在View中工作,我认为Ajax工作正常,所以我可以排除它。

以下是我尝试过的几个选项。当我将鼠标悬停在按钮上时,它们都会显示我的网页的URL,而不是Controller和Action的URL。当我单击按钮时,页面基本上刷新而不是在PublicOffers Controller中调用GetCode Action。

任何帮助深表感谢!谢谢!

选项1

<div>
    @using (Ajax.BeginForm("GetCode", "PublicOffers", null, new AjaxOptions()
    {
     UpdateTargetId = "detailsDiv",
     InsertionMode = InsertionMode.Replace,
     HttpMethod = "GET",
     OnBegin = "onStart",
     OnComplete = "onComplete",
     OnSuccess = "myCallback"
    }))
    {
     //bool checkedOption = false;
     //@html.CheckBoxFor(x => checkedOption, new { Name = "OptIn" })

     @Html.CheckBoxFor(model => model.OptIn);
     @Html.HiddenFor(model => model.Id);

     <input type="submit" value="Get Code" class="button btn-primary" />
     }
</div>

选项2

<div>    
   @using (Ajax.BeginForm(new AjaxOptions() 
   { HttpMethod = "GET", 
     Url = "PublicOffers/GetCode", 
     InsertionMode = InsertionMode.Replace, 
     UpdateTargetId = "detailsDiv", 
     OnBegin = "onStart", 
     OnComplete = "onComplete", 
     OnSuccess = "myCallback" 
   }))
   {
       //bool checkedOption = false;
       //@Html.CheckBoxFor(x => checkedOption, new { Name = "OptIn" })
       @Html.CheckBoxFor(model => model.OptIn)
       //@Html.HiddenFor(model => model.Id, new { Name = "OfferId" })
       @Html.HiddenFor(model => model.Id);
       @Html.AntiForgeryToken()

       <input type="submit" value="Submit" />
    }
</div>
答案

这不是一个答案,但它可能会有所帮助。

首先要确保你有这个,我使用NuGet来安装它,Microsoft.jQuery.Unobtrusive.Ajax

然后确保它通过捆绑脚本或cshtml中的脚本链接发送到页面

首先是简单的模型......

namespace AjaxTest.Models
{
    public class AjaxTestModel
    {
        public bool OptIn { get; set; }

    }
}

接下来一些cshtml ...

@model AjaxTest.Models.AjaxTestModel
@{ ViewBag.Title = "AjaxTest1";}
<h2>AjaxTest1</h2>
@using (Ajax.BeginForm("AjaxTest1", "Home", null,
    new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "OnSuccess(xhr)",
        OnFailure = "OnFailure(xhr, status)"
    },
    new { id = "myform" }))
{
    @Html.CheckBoxFor(model => model.OptIn);
    <span id="lbl_message"></span>
    <br />
    <button id="btn_submit" type="submit" class="">Submit</button>
}
@section scripts{
    <script>
        $(document).ready(function () {
            console.log("ready to rock and roll....");
        });
        function OnBegin() {
            console.log("OnBegin");
        }
        function OnSuccess(xhr) {
            console.log("OnComplete");
            $("#lbl_message").text("Ok:" + xhr.responseJSON.param2);
        }
        function OnFailure(xhr, status) {
            console.log("OnFailure");
            $("#lbl_message").text("Error:" + xhr.responseJSON.param2);
        }
    </script>
}

神奇的是在控制器中,注意我正在返回一个Json对象,而不是一个视图。

public class HomeController : Controller
{
    public ActionResult AjaxTest1()
    {
        AjaxTestModel model = new AjaxTestModel();
        return View();
    }
    [HttpPost]
    public ActionResult AjaxTest1(AjaxTestModel model)
    {
        if (model.OptIn)
        {
            dynamic errorMessage = new { param1 = "param1", param2 = "You opted in." };
            HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
            return Json(errorMessage, JsonRequestBehavior.AllowGet);
        }
        else
        {
            dynamic errorMessage = new { param1 = "param1", param2 = "You opted out." };
            HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
            return Json(errorMessage, JsonRequestBehavior.AllowGet);
        }
    }
}

注意,HttpContext.Response.StatusCode将控制激活哪个Ajax回调,返回HttpStatusCode.Ok并调用OnSuccess,返回HttpStatusCode.NotFound或大多数其他错误代码,并调用OnFailure。

另一答案

我通过添加一个开始的Ajax.BeginForm方法来实现它。它几乎就像第一个实例调用第二个Ajax.BeginForm方法。由于第一种方法中没有按钮或任何其他内容,因此页面上不显示任何内容。

注意:我更改了Get to a Post,因此[ValidateAntiForgeryToken]属性可用于Controller Action。我读到它不适用于Get。

<div>
  @using (Ajax.BeginForm("GetCode", "PublicOffers", new { offerId = Model.Id }, new AjaxOptions()
  {
    //Nothing here, but for some reason without this code the Ajax.BeginForm below won't work                                        
  }))
  {
    //Nothing here, but for some reason without this code the Ajax.BeginForm below won't work    
  }
</div>

<div>
  @using (Ajax.BeginForm("GetCode", "PublicOffers", new { offerId = Model.Id },
    new AjaxOptions { OnBegin = "onStart", UpdateTargetId = "detailsDiv",
    InsertionMode = InsertionMode.Replace, HttpMethod = "Post",
    OnComplete = "onComplete",
    OnSuccess = "myCallback"},
    new { @style = "display:inline-block" }))
    {
      @Html.AntiForgeryToken()

      <div class="form-horizontal">
        <div class="form-group">
          @Html.CheckBoxFor(model => model.OptIn, new { Name = "optIn"})
        </div>
      </div>
       <input type="submit" class="button btn-primary" value="Get Code" id="get-code button" />
    }
</div>

这是我的控制器动作。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> GetCode(Guid offerId, bool optIn = false)
{
  //Code here 

  return PartialView("_OfferCode");
}

以上是关于MVC 5 Ajax.BeginForm Submit按钮调用当前页面而不是指定的Controller和Action的URL的主要内容,如果未能解决你的问题,请参考以下文章

MVC小系列Html.BeginForm与Ajax.BeginForm

MVC Ajax.BeginForm 替换奇怪的行为

MVC中的Ajax.BeginForm上传文件

MVC 4 Ajax.BeginForm 绑定网格

如何为 Ajax.BeginForm MVC 刷新和重定向脚本

Asp.net Mvc Ajax.BeginForm提交表单