MVC 5 Ajax.BeginForm Submit button calls current page instead of URL of Controller and Action specified Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Asp.Net MVC Ajax.BeginForm is not submitting via AjaxASP.Net MVC 3.0 Ajax.BeginForm is redirecting to a Page?ASP.NET AJAX.BeginForm sends multiple requestsAjax.BeginForm redirects action page(MVC 4)Ajax.BeginForm with OnBegin prevent action to be calledPost data with Ajax.BeginForm to a controller action having full site nameAjax.BeginForm with ASP.NET MVC 4 not calling controller actionAjax.BeginForm ignores action and controller defined in parameters in MVC 5MVC 5 get value of CheckBox Checked in controller with Ajax.BeginFormredirect to action result on Ajax.BeginForm Post to MVC controller

Why is my ESD wriststrap failing with nitrile gloves on?

Multiple OR (||) Conditions in If Statement

An adverb for when you're not exaggerating

Selecting user stories during sprint planning

Project Euler #1 in C++

How often does castling occur in grandmaster games?

Why doesn't SQL Optimizer use my constraint?

Take 2! Is this homebrew Lady of Pain warlock patron balanced?

Illegal assignment from sObject to Id

ArcGIS Pro Python arcpy.CreatePersonalGDB_management

Does the Weapon Master feat grant you a fighting style?

How do I find out the mythology and history of my Fortress?

What do you call the main part of a joke?

Is there any word for a place full of confusion?

Dating a Former Employee

Is there hard evidence that the grant peer review system performs significantly better than random?

How were pictures turned from film to a big picture in a picture frame before digital scanning?

Did Krishna say in Bhagavad Gita "I am in every living being"

How does light 'choose' between wave and particle behaviour?

Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?

Most bit efficient text communication method?

How would a mousetrap for use in space work?

What was the first language to use conditional keywords?

Crossing US/Canada Border for less than 24 hours



MVC 5 Ajax.BeginForm Submit button calls current page instead of URL of Controller and Action specified



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Asp.Net MVC Ajax.BeginForm is not submitting via AjaxASP.Net MVC 3.0 Ajax.BeginForm is redirecting to a Page?ASP.NET AJAX.BeginForm sends multiple requestsAjax.BeginForm redirects action page(MVC 4)Ajax.BeginForm with OnBegin prevent action to be calledPost data with Ajax.BeginForm to a controller action having full site nameAjax.BeginForm with ASP.NET MVC 4 not calling controller actionAjax.BeginForm ignores action and controller defined in parameters in MVC 5MVC 5 get value of CheckBox Checked in controller with Ajax.BeginFormredirect to action result on Ajax.BeginForm Post to MVC controller



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm trying to use Ajax.BeginForm, so I can pass the value of the checkbox to my Controller Action.



I was using @Ajax.ActionLink, but I can't get the value of the newly introduced checkbox, so I want to use Ajax.BeginForm going forward.



Since @Ajax.ActionLink is working in the View, I assume that Ajax is working properly, so I can rule that out.



Here are a couple of options I have tried. When I hover over the buttons, they both display the URL of my web page instead of the URL of the Controller and Action. When I click on the buttons, the page basically refreshes instead of calling the GetCode Action in the PublicOffers Controller.



Any help is much appreciated! Thanks!



Option 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>


Option 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>









share|improve this question



















  • 1





    Can you provide the controller code for Option 1?

    – vscoder
    Mar 8 at 23:05











  • I added it to my answer, so people could see how to pass a checkbox value to a Controller.

    – Dumber_Texan2
    Mar 9 at 20:07

















0















I'm trying to use Ajax.BeginForm, so I can pass the value of the checkbox to my Controller Action.



I was using @Ajax.ActionLink, but I can't get the value of the newly introduced checkbox, so I want to use Ajax.BeginForm going forward.



Since @Ajax.ActionLink is working in the View, I assume that Ajax is working properly, so I can rule that out.



Here are a couple of options I have tried. When I hover over the buttons, they both display the URL of my web page instead of the URL of the Controller and Action. When I click on the buttons, the page basically refreshes instead of calling the GetCode Action in the PublicOffers Controller.



Any help is much appreciated! Thanks!



Option 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>


Option 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>









share|improve this question



















  • 1





    Can you provide the controller code for Option 1?

    – vscoder
    Mar 8 at 23:05











  • I added it to my answer, so people could see how to pass a checkbox value to a Controller.

    – Dumber_Texan2
    Mar 9 at 20:07













0












0








0








I'm trying to use Ajax.BeginForm, so I can pass the value of the checkbox to my Controller Action.



I was using @Ajax.ActionLink, but I can't get the value of the newly introduced checkbox, so I want to use Ajax.BeginForm going forward.



Since @Ajax.ActionLink is working in the View, I assume that Ajax is working properly, so I can rule that out.



Here are a couple of options I have tried. When I hover over the buttons, they both display the URL of my web page instead of the URL of the Controller and Action. When I click on the buttons, the page basically refreshes instead of calling the GetCode Action in the PublicOffers Controller.



Any help is much appreciated! Thanks!



Option 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>


Option 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>









share|improve this question
















I'm trying to use Ajax.BeginForm, so I can pass the value of the checkbox to my Controller Action.



I was using @Ajax.ActionLink, but I can't get the value of the newly introduced checkbox, so I want to use Ajax.BeginForm going forward.



Since @Ajax.ActionLink is working in the View, I assume that Ajax is working properly, so I can rule that out.



Here are a couple of options I have tried. When I hover over the buttons, they both display the URL of my web page instead of the URL of the Controller and Action. When I click on the buttons, the page basically refreshes instead of calling the GetCode Action in the PublicOffers Controller.



Any help is much appreciated! Thanks!



Option 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>


Option 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>






asp.net-mvc-5 ajax.beginform






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 23:19







Dumber_Texan2

















asked Mar 8 at 19:52









Dumber_Texan2Dumber_Texan2

1128




1128







  • 1





    Can you provide the controller code for Option 1?

    – vscoder
    Mar 8 at 23:05











  • I added it to my answer, so people could see how to pass a checkbox value to a Controller.

    – Dumber_Texan2
    Mar 9 at 20:07












  • 1





    Can you provide the controller code for Option 1?

    – vscoder
    Mar 8 at 23:05











  • I added it to my answer, so people could see how to pass a checkbox value to a Controller.

    – Dumber_Texan2
    Mar 9 at 20:07







1




1





Can you provide the controller code for Option 1?

– vscoder
Mar 8 at 23:05





Can you provide the controller code for Option 1?

– vscoder
Mar 8 at 23:05













I added it to my answer, so people could see how to pass a checkbox value to a Controller.

– Dumber_Texan2
Mar 9 at 20:07





I added it to my answer, so people could see how to pass a checkbox value to a Controller.

– Dumber_Texan2
Mar 9 at 20:07












2 Answers
2






active

oldest

votes


















1














This is not exactly an answer but it might help.



First be sure you have this, I use NuGet to install it,
Microsoft.jQuery.Unobtrusive.Ajax



Then be sure it gets emitted to the page, either though bundle scripts or a script link in the cshtml



First a simple model...



namespace AjaxTest.Models

public class AjaxTestModel

public bool OptIn get; set;





Next some 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>



The magic is in the controller, notice that I am returning a Json object, not a view.



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);





Note, The HttpContext.Response.StatusCode will control which Ajax callback is activate, return HttpStatusCode.Ok and the OnSuccess gets called, return the HttpStatusCode.NotFound, or most any other error code, and the OnFailure will get called.






share|improve this answer

























  • Thanks for the help! I got it working, but I did not use your method. Please see my answer below. I have no idea why this works.

    – Dumber_Texan2
    Mar 9 at 19:47











  • If it helped you can click the 'helped' icon, bump my rep :))

    – vscoder
    Mar 9 at 19:53


















0














I got it to work by adding a beginning Ajax.BeginForm method. It's almost like the first instance invokes the second Ajax.BeginForm method. Since there is no button or anything else in the first method, nothing displays on the page.



NOTE: I changed my Get to a Post so the [ValidateAntiForgeryToken] attribute would work on the Controller Action. I read that it would not work with a 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>


Here is my Controller Action.



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

//Code here

return PartialView("_OfferCode");






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55070108%2fmvc-5-ajax-beginform-submit-button-calls-current-page-instead-of-url-of-controll%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    This is not exactly an answer but it might help.



    First be sure you have this, I use NuGet to install it,
    Microsoft.jQuery.Unobtrusive.Ajax



    Then be sure it gets emitted to the page, either though bundle scripts or a script link in the cshtml



    First a simple model...



    namespace AjaxTest.Models

    public class AjaxTestModel

    public bool OptIn get; set;





    Next some 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>



    The magic is in the controller, notice that I am returning a Json object, not a view.



    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);





    Note, The HttpContext.Response.StatusCode will control which Ajax callback is activate, return HttpStatusCode.Ok and the OnSuccess gets called, return the HttpStatusCode.NotFound, or most any other error code, and the OnFailure will get called.






    share|improve this answer

























    • Thanks for the help! I got it working, but I did not use your method. Please see my answer below. I have no idea why this works.

      – Dumber_Texan2
      Mar 9 at 19:47











    • If it helped you can click the 'helped' icon, bump my rep :))

      – vscoder
      Mar 9 at 19:53















    1














    This is not exactly an answer but it might help.



    First be sure you have this, I use NuGet to install it,
    Microsoft.jQuery.Unobtrusive.Ajax



    Then be sure it gets emitted to the page, either though bundle scripts or a script link in the cshtml



    First a simple model...



    namespace AjaxTest.Models

    public class AjaxTestModel

    public bool OptIn get; set;





    Next some 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>



    The magic is in the controller, notice that I am returning a Json object, not a view.



    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);





    Note, The HttpContext.Response.StatusCode will control which Ajax callback is activate, return HttpStatusCode.Ok and the OnSuccess gets called, return the HttpStatusCode.NotFound, or most any other error code, and the OnFailure will get called.






    share|improve this answer

























    • Thanks for the help! I got it working, but I did not use your method. Please see my answer below. I have no idea why this works.

      – Dumber_Texan2
      Mar 9 at 19:47











    • If it helped you can click the 'helped' icon, bump my rep :))

      – vscoder
      Mar 9 at 19:53













    1












    1








    1







    This is not exactly an answer but it might help.



    First be sure you have this, I use NuGet to install it,
    Microsoft.jQuery.Unobtrusive.Ajax



    Then be sure it gets emitted to the page, either though bundle scripts or a script link in the cshtml



    First a simple model...



    namespace AjaxTest.Models

    public class AjaxTestModel

    public bool OptIn get; set;





    Next some 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>



    The magic is in the controller, notice that I am returning a Json object, not a view.



    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);





    Note, The HttpContext.Response.StatusCode will control which Ajax callback is activate, return HttpStatusCode.Ok and the OnSuccess gets called, return the HttpStatusCode.NotFound, or most any other error code, and the OnFailure will get called.






    share|improve this answer















    This is not exactly an answer but it might help.



    First be sure you have this, I use NuGet to install it,
    Microsoft.jQuery.Unobtrusive.Ajax



    Then be sure it gets emitted to the page, either though bundle scripts or a script link in the cshtml



    First a simple model...



    namespace AjaxTest.Models

    public class AjaxTestModel

    public bool OptIn get; set;





    Next some 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>



    The magic is in the controller, notice that I am returning a Json object, not a view.



    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);





    Note, The HttpContext.Response.StatusCode will control which Ajax callback is activate, return HttpStatusCode.Ok and the OnSuccess gets called, return the HttpStatusCode.NotFound, or most any other error code, and the OnFailure will get called.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 8 at 23:37

























    answered Mar 8 at 23:26









    vscodervscoder

    1499




    1499












    • Thanks for the help! I got it working, but I did not use your method. Please see my answer below. I have no idea why this works.

      – Dumber_Texan2
      Mar 9 at 19:47











    • If it helped you can click the 'helped' icon, bump my rep :))

      – vscoder
      Mar 9 at 19:53

















    • Thanks for the help! I got it working, but I did not use your method. Please see my answer below. I have no idea why this works.

      – Dumber_Texan2
      Mar 9 at 19:47











    • If it helped you can click the 'helped' icon, bump my rep :))

      – vscoder
      Mar 9 at 19:53
















    Thanks for the help! I got it working, but I did not use your method. Please see my answer below. I have no idea why this works.

    – Dumber_Texan2
    Mar 9 at 19:47





    Thanks for the help! I got it working, but I did not use your method. Please see my answer below. I have no idea why this works.

    – Dumber_Texan2
    Mar 9 at 19:47













    If it helped you can click the 'helped' icon, bump my rep :))

    – vscoder
    Mar 9 at 19:53





    If it helped you can click the 'helped' icon, bump my rep :))

    – vscoder
    Mar 9 at 19:53













    0














    I got it to work by adding a beginning Ajax.BeginForm method. It's almost like the first instance invokes the second Ajax.BeginForm method. Since there is no button or anything else in the first method, nothing displays on the page.



    NOTE: I changed my Get to a Post so the [ValidateAntiForgeryToken] attribute would work on the Controller Action. I read that it would not work with a 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>


    Here is my Controller Action.



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

    //Code here

    return PartialView("_OfferCode");






    share|improve this answer





























      0














      I got it to work by adding a beginning Ajax.BeginForm method. It's almost like the first instance invokes the second Ajax.BeginForm method. Since there is no button or anything else in the first method, nothing displays on the page.



      NOTE: I changed my Get to a Post so the [ValidateAntiForgeryToken] attribute would work on the Controller Action. I read that it would not work with a 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>


      Here is my Controller Action.



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

      //Code here

      return PartialView("_OfferCode");






      share|improve this answer



























        0












        0








        0







        I got it to work by adding a beginning Ajax.BeginForm method. It's almost like the first instance invokes the second Ajax.BeginForm method. Since there is no button or anything else in the first method, nothing displays on the page.



        NOTE: I changed my Get to a Post so the [ValidateAntiForgeryToken] attribute would work on the Controller Action. I read that it would not work with a 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>


        Here is my Controller Action.



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

        //Code here

        return PartialView("_OfferCode");






        share|improve this answer















        I got it to work by adding a beginning Ajax.BeginForm method. It's almost like the first instance invokes the second Ajax.BeginForm method. Since there is no button or anything else in the first method, nothing displays on the page.



        NOTE: I changed my Get to a Post so the [ValidateAntiForgeryToken] attribute would work on the Controller Action. I read that it would not work with a 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>


        Here is my Controller Action.



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

        //Code here

        return PartialView("_OfferCode");







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 9 at 20:46

























        answered Mar 9 at 20:01









        Dumber_Texan2Dumber_Texan2

        1128




        1128



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55070108%2fmvc-5-ajax-beginform-submit-button-calls-current-page-instead-of-url-of-controll%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

            Алба-Юлія

            Захаров Федір Захарович