【问题标题】:MVC 5 Ajax.BeginForm Submit button calls current page instead of URL of Controller and Action specifiedMVC 5 Ajax.BeginForm 提交按钮调用当前页面而不是控制器的 URL 和指定的操作
【发布时间】:2019-03-08 19:52:36
【问题描述】:

我正在尝试使用 Ajax.BeginForm,因此我可以将复选框的值传递给我的控制器操作。

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

由于@Ajax.ActionLink 在视图中工作,我假设 Ajax 工作正常,所以我可以排除这种情况。

这是我尝试过的几个选项。当我将鼠标悬停在按钮上时,它们都显示我的网页的 URL,而不是控制器和操作的 URL。当我点击按钮时,页面基本上会刷新,而不是在 PublicOffers 控制器中调用 GetCode 操作。

非常感谢任何帮助!谢谢!

选项 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>

【问题讨论】:

  • 能否提供选项1的控制器代码?
  • 我将它添加到我的答案中,这样人们就可以看到如何将复选框值传递给控制器​​。

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


【解决方案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。

【讨论】:

  • 感谢您的帮助!我得到了它的工作,但我没有使用你的方法。请看下面我的回答。我不知道为什么会这样。
  • 如果对您有帮助,您可以点击“帮助”图标,点击我的代表 :))
【解决方案2】:

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

注意:我将 Get 更改为 Post,因此 [ValidateAntiForgeryToken] 属性将适用于控制器操作。我读到它不适用于 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");
}

【讨论】:

    猜你喜欢
    • 2019-12-17
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    相关资源
    最近更新 更多