MVC 5 Ajax.BeginForm提交按钮将调用当前页面,而不是指定控制器和操作的URL

时间:2019-03-08 19:52:36

标签: asp.net-mvc-5 ajax.beginform

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

我使用的是@ Ajax.ActionLink,但无法获取新引入的复选框的值,因此我想继续使用Ajax.BeginForm。

由于@ Ajax.ActionLink在View中工作,因此我认为Ajax正常工作,因此可以排除这一点。

以下是我尝试过的几种选择。当我将鼠标悬停在按钮上时,它们都显示我网页的URL,而不是Controller和Action的URL。当我单击按钮时,页面基本上会刷新,而不是在PublicOffers控制器中调用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>

2 个答案:

答案 0 :(得分:1)

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

首先请确保您拥有此文件,我使用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。

答案 1 :(得分:0)

我通过添加一个开始的Ajax.BeginForm方法使其工作。几乎就像第一个实例调用第二个Ajax.BeginForm方法一样。由于第一种方法中没有按钮或其他任何东西,因此页面上没有任何显示。

注意:我将我的获取更改为帖子,因此[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");
}