Why is Ajax.BeginForm not working? - c#

I looked at several similar questions, but I can't get it working.
I have some radio buttons in a form. Instead of selecting the option and clicking the submit button, I want to submit the form when the user clicks a radio button.
So I hid the submit button and placed a javascript function that emulates the click of the button (I also tried to get it working with the button click, but this doesn't seem to be the problem).
In my View I have:
<script type="text/javascript" src="/Scripts/jquery-1.9.1/jquery-1.9.1.min.js" ></script>
<script type="text/javascript" src="/Scripts/jquery-1.9.1/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function change() {
$('#buttonradio').click();
}
</script>
<h2>Dashboard</h2>
<div class="Dashboard" id="itemsDshBrd" style="overflow:auto;height:97%;">
<div id="DshBrdRadioGroup" style="float:right;font-size:small">
<% using (Ajax.BeginForm("Index", "DshBrd", new { value = 1 }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "stations" })) { %>
<input class="radioclass" id="r1" name="radiogroup" type="radio" value="1" onclick="change()" checked/> A
<input class="radioclass" id="r2" name="radiogroup" type="radio" value="2" onclick="change()"/> B
<input class="radioclass" id="r3" name="radiogroup" type="radio" value="3" onclick="change()"/> C
<input class="radioclass" id="r4" name="radiogroup" type="radio" value="4" onclick="change()"/> D
<input id="buttonradio" type="submit" value="Submit" style="visibility:hidden"/>
<% } %>
</div>
<div id="stations">
<% Html.RenderPartial("~/Views/DshBrd/Stations.ascx"); %>
</div>
</div>
*I know that I'm sending value = 1.
In my controller I have:
[HttpPost]
public ActionResult Index(int value)
{
if (Request.IsAjaxRequest())
{
return PartialView("~/Views/DshBrd/Stations.aspx");
}
return View("~/Views/DshBrd/Index.aspx");
}
Where Request.IsAjaxRequest() is never true.
My Web.Config is also OK:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Any ideas?

I don't think you're submitting the form correctly.
Try removing the submit button altogether, and replacing your change code with:
function change() {
$("#DshBrdRadioGroup form").submit();
}
It also sounds like your unobtrusive ajax isn't working correctly. Check the following:
ClientValidationEnabled is true in your web.config app settings.
UnobtrusiveJavaScriptEnabled is true in your web.config app settings.
Your referencing jquery.unobtrusive-ajax.min.js script on your page somewhere.

I thinks this issue with your module binder . change you variable name value to radiogroup on your action.

First, you are trying to do a regular post not through AJAX from what you are describing. It will never be true.
So, you need to use something like http://malsup.com/jquery/form/ which makes it easy to do it from AJAX.
Once you are using AJAX to do your submits, you really don't have to use onclick in each radio button element. I would have done it like the following assuming those radio buttons are the only radio buttons using the class radioclass:
$('.radioclass').click(function () {
$(this).parents('form:first').trigger('submit');
});

Related

Radio Submit Button Form and Redirect

I am wanting to redirect to another page but at the same time being able to grab the details of the button that was selected. I was reading up on how onsubmit works with HTML and radio buttons work. Prior to adding buttons, I had a button and whenever it was clicked it would redirect me to the next page. I still want to do the same thing, just being able to add radio buttons to the view and submit that radio button so that way I can grab the information from the button that was selected.
I attempted:
#{
ViewData["Title"] = "Index";
}
<h2>Customer</h2>
<form method="POST">
<input type="radio" value="1" /><label>Valid</label>
<input type="radio" value="2" /><label>Wrong</label>
<input type="radio" value="3" /><label>InValid</label>
<a href="#("window.location.href='" + #Url.Action("SecIndex", "Second") + "'");">
<input type="submit" value="Address Validation" />
</a>
However, this does not redirect me to the page that I needed it to redirect to. I also noticed that once I select buttons I cannot unselect, is that apart of the radio button feature?
I also noticed that once I select buttons I cannot unselect, is that apart of the radio button feature
Yes. That's how it works.
I still want to do the same thing, just being able to add radio buttons to the view and submit that radio button so that way I can
grab the information from the button that was selected.
If you want to post the selected value to backend, you could set name for radio buttons. Because model binding system will bind value by name.
View:
<form method="POST" asp-action="SecIndex" asp-controller="Second">
<input type="radio" value="1" name="Status"/><label>Valid</label>
<input type="radio" value="2" name="Status"/><label>Wrong</label>
<input type="radio" value="3" name="Status"/><label>InValid</label>
<input type="submit" value="Address Validation" />
</form>
Controller:
public class SecondController : Controller
{
[HttpPost]
public IActionResult SecIndex(string Status)
// you can get "1" or "2" or "3" which based on your checked radio button
{
return RedirectToAction("Privacy");
}
}
HTML doesn't have store capability. you can't grab data without a programming language. But you can click to redirect to another page.
Use the button tag and use the anchor tag in the button, rather than -

ASP.NET MVC Alternate #URIaction methods in controller linked to radio button

I have two methods in my asp.net mvc controller which search the google maps Places API to perform an autocomplete action as the user types in text.
In the background I understand that the data-otf-autocomplete function uses JQUERY UI autocomplete in the background to call these methods on the form. I have to be honest and admit I don't fully understand the JQUERY UI piece as I have adapted it from another the OdetoCode sample from the AJAX lesson on Scott Allen's excellent Pluralsight course Building Applications with ASP.NET MVC4 (Great course btw). The original code from Scott's course linked to a local database to return JSON to complete an autocomplete function which I've adapted to connect to the Google MAPS Places API.
Right now I have two search boxes each linked to a different methods on the controller. One uses the locality search (best suited to approximate addresses, most rural addresses here in Ireland fall into that category) while another is suitable for exact street addresses.
Is it possible to wire these two up to a radio button control in my view so you have a single search box and depending on the radio button option selected (say locality/address) it automatically routes the request to the associated method controller
#model IPagedList<RestaurantListViewModel>
#{
ViewBag.Title = "Home Page";
}
<form method="get" action="#Url.Action("Index")"
data-otf-ajax="true" data-otf-target="#List">
<input type="search" name="searchTerm" data-otf-autocomplete="#Url.Action("Autocomplete_Address")" />
</form>
<form method="get" action="#Url.Action("Index")"
data-otf-ajax="true" data-otf-target="#List">
<input type="search" name="searchTerm" data-otf-autocomplete="#Url.Action("Autocomplete_Locality")" />
</form>
#Html.Partial("_Restaurants", Model)
Cant you just have the search box and 2 radio buttons beside it one for each search option.
<input type="radio" name="SearchType" value="local" checked>Locality
<input type="radio" name="SearchType" value="exact">Exact Address
You just need one form then, posting to a method in the controller, in the method check for the value of the radio button and run your logic based on this.
UPDATE
Razor View:
#using (Html.BeginForm("ControllerMethod", "YourController", null, FormMethod.Post))
{
<input type="radio" name="SearchType" value="local" checked>Locality
<input type="radio" name="SearchType" value="exact">Exact Address
}
ControllerMethod
[HttpPost]
public ActionResult ControllerMethod(FormCollection form)
{
var SearchType = form["SearchType"];
........
}
Fully working code using Stephen Muecke's suggestion
#model IPagedList<RestaurantListViewModel>
#{
ViewBag.Title = "Home Page";
}
<script type = "text/javascript" >
function ShowHideDiv() {
var chkAddress = document.getElementById("chkAddress");
var inputAddbox = document.getElementById("inputAddress");
inputAddbox.style.display = chkAddress.checked ? "block" : "none";
var chkLocality = document.getElementById("chkLocality");
var inputLocality = document.getElementById("inputLocality");
inputLocality.style.display = chkLocality.checked ? "block" : "none";
}
</script>
<form method="get" action="#Url.Action("Index")"
data-otf-ajax="true" data-otf-target="#restaurantList">
<div>
<input type="search" id="inputAddress" name="searchTerm" data-otf-autocomplete="#Url.Action("Autocomplete_Address")" checked/>
<input type="search" id="inputLocality" name="searchTerm" data-otf-autocomplete="#Url.Action("Autocomplete_Locality")" />
</div>
<label for="chkAddress">
<input type="radio" id="chkAddress" name="chkType" onclick="ShowHideDiv()" />
Search by Address
</label>
<label for="chkLocality">
<input type="radio" id="chkLocality" name="chkType" onclick="ShowHideDiv()" />
Search by Location
</label>
</form>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript">
$(document).ready(function () {
$("#inputLocality").hide();
$("#chkAddress").prop('checked', true);
});
</script>
}

MVC3 Ajax.BeginForm OnSuccess Doesn't Run in Firefox

FINAL EDIT:
After following the answer from Darin Dimitrov, I have found that the problem ended up being that the AJAX call to the Controller's method UpdateForm() was returning an empty string. This was a modification that I found necessary some time ago after experiencing a different problem. Passing an empty string was causing Firefox's parser to choke (while Chrome and IE didn't care, apparently) so I replaced the empty string with an empty div.
Edit:
Thanks to Darin Dimitrov's suggestions below, I have found that the reason I was having trouble is due to an error being thrown whenever the form in question is being submitted.
The error reads "Node cannot be inserted at the specified point in the heirarchy". This is thrown each and every time the form is submitted. I noticed in the POST data that it seems to think this is an XMLHttpRequest. Is that the cause (the AJAX request in question is just returning HTML)? Here is the POST data from Firebug:
This error reads "XML Parsing Error -- No Element Found".
FYI - the HTML being returned is always an empty string...
I have an MVC3 application running on IIS7. In one of my views, I have a form being built using a Microsoft HTML helper function:
#using (Ajax.BeginForm("UpdateForm", new AjaxOptions { UpdateTargetId = "TargetDiv", InsertionMode = InsertionMode.InsertAfter, OnSuccess = "ClearTextBox" }))
{
#Html.TextArea("txtInput", new { id = "txtInput", cols = "20", rows = "5", wrap = "virtual" })
<input id="send" class="button" type="submit" value="Send"/><br />
}
This generates the following HTML when the Controller provides this view:
<form action="/RootName/ControllerName/UpdateForm" data-ajax="true" data-ajax-mode="after" data-ajax-success="ClearTextBox" data-ajax-update="#TargetDiv" id="form0" method="post">
<textarea cols="20" id="txtInput" name="txtInput" rows="5" wrap="virtual"></textarea>
<input id="send" class="button" type="submit" value="Send"><br>
</form>
What I'm basically trying to do here is take the text inside the TextArea called txtInput and append it to the end of the Div called TargetDiv whenever the Send button above is clicked and clear out the text from txtInput after the appending is complete by means of the ClearTextBox() method (Javascript). The append always works in every browser; and when I run in Internet Explorer or Chrome, the clearing of the text works just fine. However, Firefox doesn't seem to want to call the ClearTextBox() method.
Is Firefox not compatible with this data-ajax-success option in the form signature?
Things I've Tried
I found this guy:
Ajax.BeginForm doesn't call onSuccess
The solution is to add this script:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
I am calling this script:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
...but I tried swapping it out just in case. No joy.
I was asked to try changing the method call to include parentheses by some folks in the C# chat room so that the HTML came out like this:
<form action="/WebChat/TMWC/UpdateForm" data-ajax="true" data-ajax-mode="after" data-ajax-success="ClearTextBox()" data-ajax-update="#chatText" id="form0" method="post">
<textarea cols="20" id="txtInput" name="txtInput" rows="5" wrap="virtual"></textarea>
<input id="send" class="button" type="submit" value="Send"><br>
</form>
But that didn't help.
The folks in C# Chat also suggested I replace the Javascript call with an alert - something like this:
<form action="/WebChat/TMWC/UpdateForm" data-ajax="true" data-ajax-mode="after" data-ajax-success="alert('yo!')" data-ajax-update="#chatText" id="form0" method="post">
<textarea cols="20" id="txtInput" name="txtInput" rows="5" wrap="virtual"></textarea>
<input id="send" class="button" type="submit" value="Send"><br>
</form>
While Chrome pops the message box, Firefox does not!
Status no repro in a newly created ASP.NET MVC 3 application.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UpdateForm()
{
return Content(DateTime.Now.ToLongTimeString());
}
}
View (~/Views/Home/Index.cshtml):
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script type="text/javascript">
function ClearTextBox() {
$('textarea').val('');
}
</script>
<form action="/Home/UpdateForm" data-ajax="true" data-ajax-mode="after" data-ajax-success="ClearTextBox" data-ajax-update="#TargetDiv" id="form0" method="post">
<textarea cols="20" id="txtInput" name="txtInput" rows="5" wrap="virtual"></textarea>
<input id="send" class="button" type="submit" value="Send"><br>
</form>
<div id="TargetDiv"></div>
Works perfectly fine in Chrome, FF and IE.
Also you might want to ensure that the Content-Type response HTTP header matches the actual response that you are sending. For example I have seen so many people send the application/json response header with some invalid JSON in the response body which produces the more sensitive parsers to choke.

c# how to enable button ontextchange without posting back

so i have a lightbox in which pops up an aspx page with textboxes and two buttons (submit - disabled and cancel - enabled). I wanted to enable my submit button ontextchange. it works fine when opened separately (not as a lightbox) but when i let it run normally with the lightbox function everytime ontextchange gets triggered the whole page refreshes disabling the lightbox.
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="OnTextChanged_AttributesEdited" autopostback="true">
protected void OnTextChanged_AttributesEdited(object sender, EventArgs e)
{
btnSubmit.Enabled = true;
}
now if i take out the "autopostback=true" it then will not trigger the the ontextchanged. was wondering if is it better if javascript will be the way to go for enabling the button or is there a way where i can prevent the postback when ontextchanged is triggered?
thanks a lot!
I think this would be a prime use for some jQuery in your application. Without posting back to the server for enabling / disabling a button, this would look a lot smoother, load faster and keep your current page state intact. An example might be as follows:
<script type="text/javascript">
$(document).ready(function() {
$("#textBox1").change(function() {
$("#btnSubmit").removeAttr("disabled");
});
});
</script>
Just put the above script tag in your HTML, just before closing the body tag.
An even better solution, however, would be to assign a specific CSS class to all the textboxes that should inherit that behaviour. Assuming that you assign a CSS class called "someCssClass" to all those textboxes, your script would then look something like this:
<script type="text/javascript">
$(document).ready(function() {
$("input.someCssClass").change(function() {
$("#btnSubmit").removeAttr("disabled");
});
});
</script>
I'd use jQuery as mentioned by #FarligOpptrenden, but if you don't have it and just want plain javascript, this should work.
Input within your lightbox:
<input type="text" id="textbox" onKeyUp="enableSubmitButton()" />
<input type="button" id="submitButton" value="Submit" />
<input type="button" id="cancelButton" value="Cancel" />
Javascript:
<script type="text/javascript">
function enableSubmitButton()
{
document.getElementById('submitButton').disabled = false;
document.getElementById('cancelButton').disabled = true;
}
</script>
You could also do your enabling/disabling buttons on load in javascript:
<script type="text/javascript">
window.onload = function () {
document.getElementById('submitButton').disabled = true;
document.getElementById('cancelButton').disabled = false;
}
</script>

HTTP POST from a ASP.NET MVC Ajax form does not include submit buttons

I am unable to determine which form submit button is clicked during an Ajax Form POST in ASP.NET MVC. I have a form that basically looks like:
<% using (Ajax.BeginForm("Edit",
new { code = Model.Code },
new AjaxOptions() {
UpdateTargetId = "resultsDiv"
})) {%>
<p>
<%= Html.TextBox("Name", Model.Name)%>
<input id="submitButton1" name="submitAction" class="ajaxSubmitButton"
type="submit" value="Button 1" />
<input id="submitButton2" name="submitAction" class="ajaxSubmitButton"
type="submit" value="Button 2" />
<input id="testHiddenValue" name="testHiddenValue"
type="hidden" value="hello world!" />
</p>
<% } %>
After a standard HTTP POST (ie. JavaScript disabled), I get access to the following POST variables:
Name = whatever
submitAction = Button 1
testHiddenValue = hello world!
However, clicking that button with JavaScript enabled does not include the submitAction value. I have verified this by inspecting the POSTs with Fiddler.
My hunch is that the Microsoft Ajax library just doesn't serialize the values of the submit buttons. In any case, how can I get around this so my controller knows which button was clicked?
Edit: Yes, it looks like a bug in the Microsoft Ajax library (see below). To workaround this, I essentially added the following jQuery code:
$(document).ready(function() {
$("#formId .ajaxSubmitButton").live("click", function() {
$("#testHiddenValue").attr("value", $(this).attr("value"));
});
});
Then in my controller, if Request.IsAjaxRequest() == true, I can check the value of #testHiddenValue. Otherwise, I can look in Request.Form["submitAction"] and determine the correct course of action from there.
Fairly clunky, but I can't really see an alternative.
See here. It looks like this is a bug. Personally I would investigate injecting the button name you wish to know about into a hidden form field as a temporary fix.

Categories