jquery form Submit success and Failure Callback - asp.net-mvc

I'm building an ASP.Net Mvc 4 app. I see that i can use a #Ajax.BeginForm to perform a POST request asynchronously. Also API seems to have an OnSuccess and On Failure parameter, which takes in the javascript function to be executed on success/failure. I've read that this works for MS Ajax, but would this work for jquery as well ? I can't seem to get it working with jquery alone
#using (Ajax.BeginForm("Create", "Comment", null, new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post",
OnSuccess = "people.successfulSave",
OnFailure = "people.saveFailure"
},
If not then, i want to do it with jquery via form submit. Currently I'm doing
$('#commentSubmitInput').click(function() {
$("#commentForm").submit();
}
to submit the form. But in my controller I'm doing some model validation and return back Html with model errors if the model is invalid, else return a partial view with updated html. Now i read that i could bind the ajax call to a function with the below syntax
$("#commentForm").bind('ajax:complete', function () {
alert('bla');
});
but, is there a way I can have success and failure callback for form submit instead ?? kind of like the Jquery ajax call syntax
$.ajax({
url: $(this).attr('ajaxUrl'),
type: 'POST',
success: function (data) {
$("#comment_" + data.Id).remove();
},
error: function (data) {
window.location.reload();
}
});
Any help/suggestion is appreciated.
Thanks in advance !

As far as I can help you is to check this: ASP.NET MVC 4 - Ajax.BeginForm and html5
And maybe this (you can get an idea or two here): MVC4 - Ajax.BeginForm and Partial view gives 'undefined'

Related

ASP.Net MVC how to invoke the action method every 10 seconds

Sorry if this is a silly question.
I have a simple MVC action method which retrieves data from database. I would like to call this action method every 10 seconds to get new data.
Basically need a way to refresh the index page, thereby calling the index method, which gets the latest data from db and display it here.
Can anyone help how to do this in asp.net 4.5 mvc EF code first.
This is a simple mvc application.
Thanks
If you`re sure that it is what you want to do, you can achieve it using jquery:
$(document).ready(function () {
setInterval(function () {
callMyAPI();
}, 10000);
});
function callMyAPI() {
return $.ajax({
url: 'YOUR_URL',
type: "GET",
dataType: "JSON"
});
}

jquery ajax call to ASP.NET MVC controller returns a MediaTypeFormatter exception

Technical Background - We're using :
1) asp.net 4.5 with VS2012
2) Durandal JS for building Single-Page-Apps (SPAs).
3) Breeze JS for querying data.
Now in my jquery ajax call, I'm calling into the Breeze Web API controller as follows:
jsonData.push({
"nodeType": vm.nodeType,
"nodeDescription": vm.nodeDescription,
"NodeDefs": ds.data() // ds dataset is coming from a grid
});
var jsonDataStr = JSON.stringify(jsonData); CONVERT DATA TO JSON
var jq = $.ajax({
url: '/api/breeze/UpdateNode/',
type: "PUT",
dataType: "json",
data:jsonDataStr,
async: false,
});
and my controller looks like this:
[HttpPut]
public SaveResult UpdateNode(JObject saveBundle)
{
SaveResult saved = new SaveResult();
return saved;
}
However I'm getting the following exception return from my jQuery FAILED EVENT :
"ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'JObject' from content with media type 'application/x-www-form-urlencoded'.
So my main question is: how can I make a successful call into my Breeze API controller with the correct JSON data ?
UPDATE AT 1:50pm EST: If I specify type: "STRING" or "JSON" in my jquery ajax call, define my parameter type as STRING in my c# Controller method, the call works fine. However, ideally I want to pass this data object as JSON and my controller should handle it properly.
Thanks in advanced.
Bob
Your controller will need [BreezeController] attribute as mentioned here http://www.breezejs.com/documentation/web-api-controller
I had to change my javascript code to NOT use the javascript array and the subsequenst jsonData.push() and stringify().
Instead I needed a straight jsonData={} object as follows :
var jsonData = JSON.stringify({
"nodeType": vm.nodeType,
"nodeDescription": vm.nodeDescription,
"NodeDefs": ds._data // gives me just the data from Kendo grid data source
});
I was then able to successfully make an ajax call to my controller as follows :
var jq = $.ajax({
url: '/api/breeze/UpdateNode',
type: "post",
dataType: "json",
contentType: 'application/json',
data: jsonData
});
All is good and I'm able to nicely put a break point inside my controller and receive the JObject parameter with issue.
thank you.
Bob

How to receive Open/Save file dialog after ajax-form post with ASP.NET MVC and jQuery

I want to be able to receive open/save dialog for a pdf file being returned from controller without using 'Html.Beginform' in ASP.NET MVC. I´m using 'Ajax.Beginform' since I can register events to fire OnBegin and OnComplete (which I think I can´t do when using Html.Beginform, or is it?).
I want to state that the problem is not creating and receiving the file from the server when using 'Html.Beginform' because that works fine, but without the events I want to use. I´m using 'Ajax.Beginform' and the file is being returned from the controller but nothing happens after that client side.
My cshtml
#using (Ajax.BeginForm("CreatePdf", "Print", null, new AjaxOptions() { LoadingElementId = "printLoading", OnSuccess = "printPageComplete"}, new { id = "exportForm" }))
{
//Stuff abbreviated
<input type="button" onclick="onPrint()" />
}
My jQuery
function onPrint()
{
//Stuff abbreviated
$("#exportForm").submit();
}
function printPageComplete(result)
{
//this 'result' variable is obviously holding the file from the controller
//stuff abbreviated
//TODO: I need to open file dialog here
}
My Controller
[HttpPost]
public ActionResult CreatePdf(FormCollection collection)
{
//Stuff abbreviated
return File(thePdf, _mimeTypes[ExportFormat.Pdf], "thePdf.pdf")
}
As you can see I´ve managed to get this far as in the printPageComplete function but I´m not sure where to go from here. Should I continue using the ajax form or should I stick with the html form and try to find other way to fire the events I so sorely need to use?
Perhaps I´m going about this all wrong and your help would be very well appreciated.
You can post a form without using Ajax.BeginForm. It is more work, but gives you more flexibility:
$('#exportForm').submit(function (e){
e.preventDefault();
//Do any validation or anything custom
$.ajax({
//set ajax settings
success: function(){
// Handle the success event
}
});
});

jQuery.Validation.Unobtrusive client side validation only works when scripts are on view page

I have an ASP.NET MVC 4 App that uses the jQuery.validation.js plugin and MVC's jQuery.validation.unobtrusive.js. I use data annotations on my view model to validate a textbox's input to be an integer.
This (nested) view is loaded within a parent view using...
<% Html.RenderPartial("New"); %>
One the first inital page load, client side validation works. But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?
Update: (Code example from webdeveloper's solution below)
$.validator.unobtrusive.parse($('form'));
Example:
var saveAndUpdate = function (url) {
var myForm = $('form', $('#TheDivThatContainsTheNewHTML'));
$.ajax({
url: url,
type: 'POST',
data: myForm.serialize(),
success: function (result) {
$('#TheDivThatContainsTheNewHTML').html(result);
$.validator.unobtrusive.parse($('#TheDivThatContainsTheNewHTML'));
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
},
dataType: 'html'
});
}
But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?
Validation applies on document ready, when you refreshing page you should manually init validation for your form.
Like this:
$.validator.unobtrusive.parse("form");
Same question: jquery.validate.unobtrusive not working with dynamic injected elements

unwanted multiple ajax request to an action in asp.net mvc

I am developing an asp.net mvc application and have ajax calls on my page. Here is a form which I load by ajax call to page :
The form is located in a partial view
<div id="CreateCultureArea">
<%
using (Ajax.BeginForm("CreateCulture", "Admin", new AjaxOptions() { OnSuccess = "handleCreateCulture" }))
{ %>
.....
<% } %>
</div>
Code Updated
The following script is located in a view :
Create Culture
<script type="text/javascript">
$('.CreateCulture').live('click', function (e) {
e.preventDefault();
var idval = this.id;
$.ajax({
url: "/Admin/CreateCulture",
dataType: 'html',
data: { id: idval },
success: function (mydata) {
$("#CultureContentArea").empty();
$("#CultureContentArea").empty().hide().append(mydata).fadeIn(2000);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
},
type: "GET"
});
return false;
})
</script>
When users click on a link with CreateCulture class, the form is loaded to page. But as I saw the requests in firebug, it calls the action multiple times. I read similar posts like mine on stackoverflow.com and most of them suggested removing repetitive "jquery.unobtrusive-ajax.min.js" calss in page, but as I saw the output page I only see on link to the "jquery.unobtrusive-ajax.min.js" script.
The problem is that #Ajax.BeginForm emits a form that has the attribute data-ajax="true". In the unobtrusive AJAX script (see the non-minified version and look for calls to asyncRequest). So by calling $.ajax yourself, you are repeating the work of #Ajax.BeginForm. Just take out your call to $.ajax and you'll see your action get called only once.
If you need to take action after the AJAX call completes, set the OnComplete property of AjaxOptions in your call to Ajax.BeginForm.
Make sure that you have not multiple .js refrence in page
<script src='/Scripts/jquery.unobtrusive-ajax.min.js'></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
The problem was that I put some scripts in partial view and each time it duplicated by loading this. So I put the scripts all in on page and problem solved.

Resources