Submitting AjaxForm with jQuery in ASP.NET MVC - asp.net-mvc

I have an ajax form in asp.net mvc which is as simple as this:
&lt% using (this.Ajax.BeginForm("LatestBlogPosts", "Blog", null, new AjaxOptions { UpdateTargetId = "blogPostPanel" }, new { id = "BlogPostForm" })) { %>
<div class="panel" id="blogPostPanel">
<img src="/images/ajax-loader.gif" alt="ajax-loader" />
</div&gt
<% } %>
I want to invoke the form submit when document is loaded. This should supposedly, call the controller's action and return a result that should be replaced with the placeholder DIV. If I add a SUBMIT button to the form, it works perfectly, but when I invoke the submit via jQuery, the whole page is refreshed, and the content returned by the server is displayed in the newly displayed page. Here's my jQuery code:
<script type="text/javascript">
$(document).ready(function() {
$("#BlogPostForm").submit();
});
</script>
Anyway to do this?

I think it may work if you use the trigger method to generate the submit event, but I think there's a less complicated way to do this using jQuery.
<div class="panel" id="blogPostPanel">
<img src="/images/ajax-loader.gif" alt="ajax-loader" />
</div>
<script type="text/javascript">
$(function() {
$('#blogPostPanel').load( '<%= Url.Action( "LatestBlogPosts", "Blog" ) %>' );
});
</script>

Related

Ajax.BeginForm helper not loading partial view into specified DIV

I am working with MVC trying to load the results of a form submission into a specific DIV.
Below is the code of my form:
<div class="segmentForm clearfix">
<% using (Ajax.BeginForm("ShopByAirCriteria", "AirOption", new AjaxOptions { UpdateTargetId = "DynamicAirOptions", InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnBegin = "return loadingBar();" }, new { #name = "AirOptionSegment_Air" }))
{ %>
<%
Html.RenderPartial("AirOneWay", Model);
%>
<br/>
<div class="agent-actions">
Load Original Data
<input type="submit" class="btn green" id="a1" name="SearchAir" value="Search" />
</div>
<% } %>
</div>
I have included the necessary js files in my site master:
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")%>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")%>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>"></script>
But somehow, the Partial view that is rendered by the AirOption/ShopByAirCriteria action method is not being loaded in the DynamicAirOptions div but in a new page.
Any idea on what the issue might be?
It was working properly when I was using the html.BeginForm helper, but I changed it to use the ajax helper instead because I need to load the results into a specific div. Is there any way to specify the TargetID with the html helper?
I would caution against using Ajax.BeginForm. It's a bit of a hold-over from Web Forms, and in my humble opinion, should never be used under any circumstances. It hides logic and therefore leads the developer pretty inevitably into a situation like yours, where it's not working and there's no obvious reason why. Explicit is always better than implicit; when you control the AJAX call, you'll always know why it does or does not work.
So, just use a regular Html.BeginForm and then tie into the submit event with some custom JavaScript. Make your AJAX call to submit the form in your event handler and then render the resulting response to the page in the div you want. Since you're already using jQuery, this is super simple:
$('#YourForm').on('submit', function (evt) {
evt.preventDefault();
$.post('/some/url', $(this).serialize(), function (response) {
$('#YourDiv').html(response); // assuming response is HTML
});
});
A side benefit to this approach is that you're not crippling the standard form. It's still just a regular old form, so if JavaScript is disabled, or not available at all (such as with many screen readers used for the blind), the form can still submit the standard old way and return a new page with the results.
Have you include jquery before jquery.unobtrusive-ajax.js? it could be also some javascript error, check Console in your browser developer tool.
I've paste your code in blank mvc4 app and works as expected.
Master:
<script src="/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.unobtrusive-ajax.js"></script>
View:
<div class="segmentForm clearfix">
<% using (Ajax.BeginForm("ShopByAirCriteria", "AirOption", new AjaxOptions { UpdateTargetId = "DynamicAirOptions", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" }, new { #name = "AirOptionSegment_Air" }))
{ %>
<div id="DynamicAirOptions">
</div>
<br/>
<input type="submit" class="btn green" id="a1" name="SearchAir" value="Search" />
<% } %>
</div>
My problem was using the following in my layout. I believe it was loading unnecessary files that were causing a conflict. It all worked fine in Edge and Safari, but the PartialView would not render inside the div on Chrome. It would display in a new page.
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
Instead of using the bundles, I went with this and Ajax.BeginForm works great!
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>

Remove Rails partial from view

My Rails app uses partials to load different pieces of the site into view. I'd like to add a close icon that removes the partial from view when clicked. Example: The user opens a folder in the app, and clicks an icon to "close" the folder. Is this possible?
Ok quick solution with jquery:
_partial.html.erb
<div id="unique">
<p>Html code here</p>
</div>
View.html.erb
<%= render :partial => 'partial' %>
<script type="text/javascript">
window.onload = function () {
$('#unique').remove()
}
</script>
removing the DOM node with jquery .remove()
http://api.jquery.com/remove/

ASP.NET MVC JQuery UI TAB - How to make post-back on each tab click. How to make it SEO friendy?

I am using jquery tab as given bellow. Clicking on each tab it make a AJAX call according to its href url. Problem is AJAX call is not SEO friendly. How i can make it SEO friendly? How to do a postback on each tab click and keep current tab as selected after postback. Also how to update url on each tab click i mean if user click on [SPECIFICATION] tab, after post back url should look like www.domnainname/cardetails/specification
I AM USING ASP.NET MVC 4.0.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function ($) {
$('#example').tabs();
});
</script>
<div id="example" class="tabs" style="width: 698px;">
<ul style="list-style: none;">
<li>Overview</li>
<li>Specifications</li>
<li>Exterior</li>
<li><a href="/Version/Details?ID=#ViewBag.versionId&grpId=2" title="tabs-4" >Interior</a></li>
<li>Dimensions</li>
<li>Feature</li>
<li>Instrument Panel</li>
</ul>
<div id="tabs-1" style="width: 698px;">
This is Tab one
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
<div id="tabs-4">
</div>
<div id="tabs-5">
</div>
<div id="tabs-6">
</div>
<div id="tabs-7">
</div>
</div>
Thanks,
#Paul
Based on what you are trying to do I would suggest the following:
Replace href="/Your/links/address" with href="#corresponding-panel"
Add a 'data-link' attribute to house your url
Subscribe to tab's select event
$(".tabs").tabs({select:function(ui, event){
if(!$(event.panel).hasClass('loaded')){
var linkURL = $(ui.currentTarget).attr('data-link');
//Ajax load has happend
if(linkURL != undefined){
//USE the 'linkURL' variable in place of '/echo/json'
$.ajax({
url: "/echo/json" ,
success:function(data){
$(event.panel).addClass('loaded').html("<h1>Some ajax content loaded from " + $(ui.currentTarget).attr('data-link') );
}
});
}
} }});​
Here is the JSFiddle example

MVC2 Ajax Form does unwanted page refresh

I am pretty new to MVC. I have my first Ajax Form here:
<div id="test"></div>
<div id="MainChatMenu">
<% using (Ajax.BeginForm("SendMessage", "MainChat", new AjaxOptions { UpdateTargetId="test"}))
{ %>
<input id="chatMessageText" type="text" maxlength="200" />
<input type="submit" value="Go"/>
<% } %>
Now, if I click the submit button, the page is reloading, goint to mysite/controller/action.
I thought that the default behaviour of the Ajax.BeginForm was exactly not to do that?
Where's my newbie mistake?
My Controller is called correctly, but data passing also doesn't work. Probably because of the same mistake?
Here's the code:
public class MainChatController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public EmptyResult SendMessage(FormCollection formValues)
{
return new EmptyResult();
}
}
Make sure you have included the necessary script libraries:
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
<% using (Ajax.BeginForm("SendMessage", "MainChat", new{}, new AjaxOptions { UpdateTargetId="test", HttpMethod="POST"})) %>

How to dispatch on the result of submiting an AJAX form in ASP.Net MVC?

In ASP.Net MVC, having a form more or less like this:
<% using (Ajax.BeginForm(new AjaxOptions() { OnSuccess="onSuccess"})) {%>
<p>
<label for="Comment">Comment:</label>
<%= Html.TextArea("Comment")%>
<%= Html.ValidationMessage("Comment", "*")%>
</p>
<p><input type="submit" value="Submit comment" /></p>
<% } %>
How can the onSuccess Javascript function know whether the result is another version of the form because it didn't validate, a comment as a div to add to the list of comments or a log in page that should be pop up for logging in?
You can define that in your returning JSON or whatever transport method you use?
Not sure if that's what you're looking for, but also: this is how the onSuccess function is called:
YourFunction(ajaxContext);
AjaxContext is defined as follows:
AjaxContext ajaxContext = new AjaxContext(request, updateElement, loadingElement, ajaxOptions.InsertionMode);
You should replace the code inside your ajax form with a new partial view, then you will return that partial view from your controller. The partial view would consist in:
<p>
<label for="Comment">Comment:</label>
<%= Html.TextArea("Comment")%>
<%= Html.ValidationMessage("Comment", "*")%>
</p>
<p><input type="submit" value="Submit comment" /></p>
This way, your partial view works just like a regular view.
Unfortunately there is no simple way to execute javascript as a response (since you are responding with a view). It would be easier if your response was a Json string, but in that case, you can't use the AjaxForm because the Json string would be rendered on screen as a result of submitting the form (and processing its response). This may work though (I haven't tried it):
<p>
<label for="Comment">Comment:</label>
<%= Html.TextArea("Comment")%>
<%= Html.ValidationMessage("Comment", "*")%>
</p>
<p><input type="submit" value="Submit comment" /></p>
<script type="text/javascript">
function processResponse(data){
// blah blah blah
}
processResponse(<%= ViewData["dataFromTheController"] %>);
</script>
Your could simply add different CSS classes to the root elements of your responses (for example .form, .comments, .login). And then (for example in jQuery):
var response = $(responseContent);
$('.form', response).each(function() {
// $(this) is form
});
$('.comments', response).each(function() {
// $(this) is comments
});
$('.login', response).each(function() {
// $(this) is login page
});
How can the onSuccess Javascript
function know whether the result is
another version of the form because it
didn't validate, a comment as a div to
add to the list of comments or a log
in page that should be pop up for
logging in?
The short answer is that it cannot unless you explicitly validate it. That's because JSON is transported as a string and when the client side Javascript gets the string.
For starters you should implicitly know what sort of object to expect. If you are calling an web service # Cars/List then you know the returned object will be a list of cars and you parse that appropriately in your client. You can run into errors which you should handle appropriately by retrying the request or logging them or showing an error message.
I would recommend you to use the jquery.form plugin, with this you can have a normal form to act like an ajax one, like this:
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>

Resources