Ajax.BeginForm not submitting form - ajax

I am doing an MVC tutorial and have hit a problem.
I changed a working view from using Html.BeginForm to Ajax.BeginForm. But the form is not submitting.
Per my research I verified that ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are both set to true in web.config. I do have the most recent version of jquery.unobtrusive-ajax,js and jquery refrenced. But still no joy.
I firebugged jquery.unobtrusive-ajax to see what it was doing. It is setting itself up on page load. But no functions are called when I click the submit button.
Here is a snippet from View Source to show how the form tag is begin set up:
<div id="formSection">
<h3>Having trouble? Send me a message</h3>
<form action="/Home/Contact" data-ajax="true" data-ajax-method="post" data-ajax-mode="replace" data-ajax-update="#formSection" id="form0" method="post">
</form>
<textarea name="message"></textarea>
<input type="submit" value="send" />
</div>

My error became apparent while asking the question. I was cleaning up the bad formatting of the HTML when I saw the end form tag was before the submit button!
I had an error in my Razor code.
#Using (Ajax.BeginForm("Contact", "Home", New AjaxOptions With {.HttpMethod = "post", .InsertionMode = InsertionMode.Replace, .UpdateTargetId = "formSection"}))
End Using
<textarea name="message"></textarea>
<input type="submit" value="send" />
Putting the End Using right after the Using closed the block of course, so the input element never got into the form.
Correct syntax:
#Using (Ajax.BeginForm("Contact", "Home", New AjaxOptions With {.HttpMethod = "post", .InsertionMode = InsertionMode.Replace, .UpdateTargetId = "formSection"}))
#<textarea name="message"></textarea>
#<input type="submit" value="send" />
End Using
It would have been nice if the generated code was formatted well, I would have seen the end form tag location much sooner.
Hopefully I help avoid a few head slaps.

Related

Updating .NET Charts using ajax.beginform

I'm using .NET Charts to create some dynamic charts from a table in a database, and each chart is a separate view, with a corresponding action in the controller.
Then they are displayed in a main view as images:
<img src="~/Controller/Chart1" class="centered" />
Now I want to be able to filter the charts by date, and I've added the parameters to the actions and a couple datepickers for a start date and an end date.
I'm trying to refresh the charts using Ajax, but I'm having trouble. Without Ajax, the filter works, but redirects to a page containing just the updated chart.
With Ajax, nothing happens, or rather, if I set the UpdateTargetId to a div it gets filled with text, like byte code or something.
This is what I'm using:
<div>
using (Ajax.BeginForm("Chart1", "controller",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "Chart1"
}))
{
<p>
<input type="text" name="begindate" class="datefield" placeholder="Begin Date" />
<input type="text" name="enddate" class="datefield" placeholder="End Date" />
<input type="submit" value="Filter" />
</p>
<img src="~/controller/Chart1" class="centered" />
</div>
How can I fix this problem?
You need to pass the dates to your action method and let the action method uses these dates to generate a filtered data set which will be used to generate the chart.
You can simply use jQuery Ajax to do this.
<div>
<input type="text" name="begindate" class="datefield" placehold="Begin Date" />
<input type="text" name="enddate" class="datefield" placeholder="End Date" />
<input type="submit" id="btnFilter" value="Filter" />
<img src="~/controller/Chart1" id="chartImg" class="centered" />
</div>
Now when user clicks the form, pass the dates
$(function(){
$("#btnFilter").click(function(e){
e.preventDefault();
var d1 = $("input[name='begindate']").val();
var d2 = $("input[name='enddate']").val();
var url = "#Url.Action("Chart1", "YourControllerName")";
url += "?beginDate=" + d1 + "&endDate=" + d2;
$("#chartImg").attr("src", url);
});
});
Now of course your action method should accept the dates and return the data as needed:
public ActionResult Chart1(DateTime beginDate,DateTime endDate)
{
// Return the chart image
}
I am using the Url.Action action method to generate the correct path to the Chart1 action method. This code will work if your JavaScript code is inside a Razor view. If your code is inside an external js file, Use the approach mentioned in this post

Prevent reload on Ajax.BeginForm

How can I prevent page reloading when submitting form in partial view? There are a lot of examples but it seems that non of them is working for me. This is what I have. Partial view (Razor) which calls this:
#using (Ajax.BeginForm("SaveReply", "Home", null, new AjaxOptions { HttpMethod = "Post" }, new { target = "_self" }))
{
<div class="input-group wall-comment-reply" style="width:100%">
#Html.Hidden("eventid", #item.EventID)
<input name="txtReply" type="text" class="form-control" placeholder="Type your message here...">
<span class="input-group-btn">
<button class="btn btn-primary" id="btn-chat" type="submit">
<i class="fa fa-reply"></i> Reply
</button>
</span>
</div>
}
Then I have my action method in the controller:
[HttpPost]
public void SaveReply(string txtReply, string eventid)
{
//some code
}
The controller action is fired but after that it is automatically redirected to localhost/home/SaveReply
Maybe the problem is that this partial view is rendered from string. I took the code from:
How to render a Razor View to a string in ASP.NET MVC 3?
Also amongs other things i tried this:
http://geekswithblogs.net/blachniet/archive/2011/08/03/walkthrough-updating-partial-views-with-unobtrusive-ajax-in-mvc-3.aspx
I would appreciate any help.
I found the problem.
It seems that you need to reference the Unobtrusive scripts. Just install them from NuGet:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
And then reference it from the View that calls the Partial View:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
And miraculosly it works without any other changes. More explanations can be found here:
[Why does Ajax.BeginForm replace my whole page?
and here:
[Why UnobtrusiveJavaScriptEnabled = true disable my ajax to work?
It seems that you need to use it if you are using Ajax.* helpers in MVC 3 and higher.

My .ajax call isn't working

I have a form on my website that pushes to my e-mail address. Previously before I wrote an ajax function the form would successfully push to my e-mail address. Only problem is when the user fills out the form it takes them to another page upon submitting the form. The HTML for my form is below.
<form id="contact" method="post" action="E-mail-form.php" name="EmailFromMyWebsite">
<label for="name">Name</label> <br>
<input type="text" name="name" class="required" placeholder="Your Name" title=" (Your name is required)"> <br />
<label for="email">E-mail</label> <br>
<input type="email" name="email" class="required email" placeholder="Name#email.com" title=" (Your email is required)"> <br />
<label for="message">Message/Comment</label> <br>
<textarea name="message" class="required" placeholder="Leave a brief message" title=" (Please leave me a brief message)"></textarea> <br />
<input type="submit" name="submit" id="submit" value="Send Message" />
</form>
</div><!-- /end #contact-form -->
The ajax call I wrote is...
$("#submit").on('click', function(){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:"formData",
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
});
My javaScript console shows no errors so I think the problem is with my jQuery logic. On Chrome when I click submit I am redirected to my homepage. On Firefox the form submits but I am redirected to another page, therefore it is completely ignoring my AJAX call. Can someone with AJAX experience tell me what I'm doing wrong? Also I would love to attach a message if the call fails. Can I add 'failure:' and for the value put a function just like I did for success?
You have two issues
your form is submitting normally
you're attempting to post the wrong data
To prevent the form from submitting you can return false from the jQuery click handler or call preventDefault from the event object.
You are sending a string "formData" as the form data instead of the string in the formData variable
$("#submit").on('click', function(event){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:formData,
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
event.preventDefault();
// or
return false;
});
There's a good chance that the normal form submit action is still taking place, even though you have an AJAX call as well. An easy fix for this may be to simply change the button type from submit to button. That way your click handler will still work, but it won't perform the default action of submitting the form on its own.
<input type="button" name="submit" id="submit" value="Send Message" />

AJAX.BeginForm PostURL being corrupted

I'm experiencing a strange problem while trying to use the Ajax.BeginForm method of ASP.NET MVC3. The form renders properly on the page with the correct action attribute. However, when the form is submitted, the "OnFailure" event is returning a "Not Found" 404 error.
If I watch the request with fiddler, I see that the post URL is "/[Object NodeList]" which is obviously invalid.
My Razor code is as follows:
#using (Ajax.BeginForm("Save", "Items", new AjaxOptions { UpdateTargetId = "itemContainer", InsertionMode = InsertionMode.Replace, OnFailure = "onFailure"}))
{
<div style="position:absolute; bottom:20px; left:200px;">
<button type="submit" id="Save" name="action" value="Save">Save</button>
<button type="submit" id="Cancel" name="action" value="Cancel">Cancel</button>
</div>
}
The problem was using "action" for the name attribute on the submit buttons. As soon as I changed the name attribute to a different value, everything started working perfectly.
I'm guessing that there is a jQuery selector in the unobtrusive ajax library that got confused.
Do you have unobtrusive JavaScript on or off in your web.config? Im first guessing here the ms Ajax library is acting goofy so enable unobtrusive so we get jquery support.
What is your form action set to? Post your form HTML element if you can .

Form Submit using a Javascript to invoke webflow transition, doesn't take the updated value on form

I am trying to invoke a form submit using javascript (jquery) to invoke a webflow transition. It works and the submit invokes the desired transition. But, the updated radio button values is not reflected on the model object which is posted.
Here is the code:
<form:form method="post" action="#" commandName="infoModel" name="pageForm">
<form:input type="input" path="testMsg" id="success" />
<input type="button" id="clearSelections" value="Clear Selections">
<div class="question">
<h4><c:out value="${infoModel.questionInfo.description}"/> </h4>
<form:radiobuttons path="infoModel.answerId"
itemValue="answerId" itemLabel="answerDescription" items="${infoModel.answers}" delimiter="<br/>" />
</div>
<input type="submit" name="_eventId_saveQualitativeInput" value="Save" id="save" />
$(document).ready(function() {
$('#tabs').tabs();
//Clear selections (copy is server-side)
$('#clearSelections').click(function() {
//$('input[type="radio"]').prop('checked', false);
$('input[type="radio"]').removeAttr('checked');
$('#save').trigger('click');
});
});
</form:form>
The form:radiobutton, generates the below html:
<div class="question">
<h4>Is this a general obligation of the entity representing a full faith and credit pledge? </h4>
<span>
<input type="radio" checked="checked" value="273" name="infoModel.answerId" id="infoModel.answerId1">
<label for="infoModel.answerId1">Yes</label>
</span>
<span><br>
<input type="radio" value="274" name="infoModel.answerId" id="infoModel.answerId2">
<label for="infoModel.answerId2">No</label>
</span>
<br>
<span class="error"></span>
</div>
The input id= "success" value is registered and when the control goes to the server, the value of input id= "success" is updated in the "infoModel" object. But the value of answerId is not updated on the "infoModel" object.
Thoughts if i am missing something in the form:radiobutton element or if there is something else wrong?
Thanks in advance!
EDIT:::::::
Thanks mico! that makes sense. I stripped of some of the code first time to make it precise, but i have a list which is being used for building the radio-buttons, below is the code:
<c:forEach items="${infoModel.list["index"]}" var="qa" varStatus="rowCount">
<div class="question">
<h4><c:out value="${question.questionInfo.description}"/> </h4>
<form:radiobuttons path="list["index"][${rowCount.index}].answerId" itemValue="answerId" itemLabel="answerDescription" items="${question.answers}" delimiter="<br/>" />
<br>
</div>
</c:forEach>
Could you please suggest how i could try this one out?
NOTE: The same code works on a regular form submit on click of a button of type submit. Its the javascript form submit which is not working. I also tried to do whatever i want to do in javascript and then invoke the button.trigger('click'); form got submitted but the changes made on form in my javascript didnt reflect.
With commandName inside a form:form tag you set "Name of the model attribute under which the form object is exposed" (see Spring Documentation). Then in path you should tell the continuation of the path inside the model attribute.
With this said I would only drop the extra word infoModel from path="infoModel.answerId" and have it rewritten as path="answerId" there under the form:radiobutton.

Resources