Invoking action method using Java script in asp.net MVC - asp.net-mvc

I have a form, I want to check the username is availability. I that I have html textbox, in Onclcik I'm calling java script function. The script has to call the Action methods in controller. Based upon the username availability it has to return either 1 or 0. I have tried Json. But its is showing "Microsoft JScript runtime error: '$' is undefined". Can anyone help me in this.

If you get that message it means you're trying to use jQuery but you haven't included the library. You can use Google's CDN.
I guess you've used Ajax to call. Something like this:
$.ajax({
type: 'POST',
url: '<%=Url.Action("Your Action", "Your Controller")%>',
data: { userName: $('#UserName').val(), password: $('#Password').val() },
dataType: 'json',
complete: function(XMLHttpRequest, textStatus) {
// User your JSON response.
}
});
If you're using a POST you have to decorate your action with the attribute [HttpPost]
and remember to specify JsonRequestBehavior.DenyGet when you return your JSON object:
[HttpPost]
public JsonResult CheckUserName(string userName, string password)
{
// notification: your object
return (Json(notification, JsonRequestBehavior.DenyGet));
}

If you are using Jquery (the $ sign), then that means that you need a script reference to jquery implementation before your javascript code that calls JSON.
script type="text/javascript" src="jquery.js"></script>
Where jquery.js is the latest version of the jquery javascript file

Related

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

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

jquery form Submit success and Failure Callback

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'

Ajax post throws A required anti-forgery token was not supplied or was invalid

I'm trying to secure my ajax posts using the anti-forgery mechanism.
First I've added the antiforgerytoken helper method call to my view
#Html.AntiForgeryToken()
and then adjusted my jquery post call
var values = $(this).serialize() + "&__RequestVerificationToken=" + $("input[name='__RequestVerificationToken']").val();
$.post(url, values)
.success(page.submitSuccess)
.error(page.submitError)
.complete(page.submitComplete);
and of course I decorated my action method with the ValidateAntiForgeryToken
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProjectCreateCommand command)
{
....
}
but after submiting the form it throws the A required anti-forgery token was not supplied or was invalid error.
I've deleted the token cookie and also I've restarted the browser.
Am I missing something ?
if you use $(form).serialize(); it will serialize all input tags, so you can do it by the $.post jquery method. Try something like this:
$("#you_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr("action"), // get url from action attribute, your route setted by the Html.BeginForm()
data: $(this).serialize(), // serialize all input tags from this form
success: page.submitSuccess;
});
});
There is no problem using #Html.AntiForgeryToken(), serialize method will add this together.
Take a look at this link: http://api.jquery.com/jQuery.post/

MVC : How does it work a ajax call to controller action passing less parameters than what is required but it still works?

I have this function on my view page
var params = {
Param1: $('#as').val(),
Param2: $('input[name=dswe]').val(),
Param3: $('inpu`enter code here`t:radio[name=wer]:checked').val()
}
$.ajax({
type: 'POST',
url: 'controlleractionname',
data: params,
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
},
success: function(html) {
$('#Message').html('MRR Received Date SAVED');
closeDialog();
},
cache: false
});
This calls the following action on controller page
public string controlleractionname(string param1, DateTime param2, int param3, Classdata data1)
{
code is here
}
Now, my question is this works perfectly fine, but I wanted to know how is this working ? since I am passing only 3 parameters from ajax to this controller action. The fourth parameter is a datacontract class of a WCF service.
I am asking because this is a working application and I am new to this project and trying to understand the functionality.
Any input is appreciated.
When ASP.NET MVC receives a request first it matches it to a route. You must have a route that matches the URL that you are posting to.
Once ASP.NET MVC has found a match it will instantiate the controller that was indicated in the route and call the action method also indicated on the route.
At this point ASP.NET MVC goes through a process where it tries to find information from the HTTP request (form values, query string parameters, et cetera) and matches it to the parameters defined in your method definition for the action. For example, if MVC finds a query string parameter "param1" it will automatically pass the query string value to the "param1" in your method. If it cannot find a value in the request it will pass a default value (e.g. null for strings, 0 for integers.)
This is a simplified explanation but I hope it gives you an idea of what's going on.

Resources