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>
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...
Next some cshtml...
The magic is in the controller, notice that I am returning a Json object, not a view.
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.