I am new to MVC programming.I am working on a simple POC application that displays/edits data from Database.
I have 2 views and 2 controllers. On one of them the JQuery AJAX call to MVC controller action method is working fine. But not on the other one (In here, the AJAX call is not triggering the Action method).
Can anyone had this situation before???
The JQuery code is below:
$('#ddlZones').change(function () {
var value = $('#ddlZones option:selected').val();
// alert(value); var status = $('#ddlStatus option:selected').val();
// alert(status); $('#lstResources').children().remove();
$('#lstBeds').children().remove();
$.ajax({ url: 'FillResources', type: 'POST',
data: JSON.stringify({ ZoneId: value }),
dataType: 'json', contentType: 'application/json',
success: function (result) {
for (var r in result) {
$('#lstResources').append('<option value="' + result[r].Value + '">' + result[r].Text + '</option>');
}
}
});
});
Thanks
Latha
Check the controller url is called or not,
Also in data parameter you can call it simply like { ZoneId: value } instead of
JSON.stringify({ ZoneId: value }),
At server side get this parameter by using $_POST if you are using PHP
in controller, also check in console that, you are getting json from server side or not.
$.ajax({ url: 'FillResources', type: 'POST',
data:{ ZoneId: value },
dataType: 'json', contentType: 'application/json',
success: function (result) {
for (var r in result) {
$('#lstResources').append('<option value="' + result[r].Value + '">' + result[r].Text + '</option>');
}
}
});
Please check the request and the response in the browser. You can use the inbuilt ones in IE/Chrome/FF(Firebug) or fiddler. It probably is just a routing issue if this is ASP.NET MVC.
Specifically, look for what your request url is and what is the HTTP response from the server.
It is always a good practice to specify both the controller and actions in the routing urls to avoid any such errors.
Another thing to check will be if the change function is actually being called? You can put a console.log before the ajax request to make sure that this is not the case.
Related
This is the first time i'm working with Web API. i'm trying to call a web api through a jquery ajax call. ajax call hits the web api action successfully but the string parameter "xx" is always null.
Ajax call
var x = "chamara";
$.ajax({
type: 'POST',
url: 'http://localhost:1557/api/values/mytest',
data: '{"xx":"' + x + '"}',
dataType: 'json',
});
Web Api action.
[AcceptVerbs("GET", "POST")]
public void mytest([FromBody]string xx)
{
string a = xx;
}
web api routes configuration.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional }
);
Try this:
var x = "chamara";
$.ajax({
type: 'POST',
url: 'http://localhost:1557/api/values/mytest',
data: { '' : x },
dataType: 'json',
});
I encountered the same thing this morning. I'm not sure why and I feel like there should be a better way, but it worked for me.
Alternatively, see this SO question where the solutions suggest setting the contentType to application/json.
I wrote this simple code in JQuery to solve all my Microsoft .NET WebApi woes:
$.webApi = function (method, url, data) {
return $.ajax(url, {
type: method,
data: typeof (data) === "object" ? JSON.stringify(data) : data,
dataType: "json",
contentType: "application/json"
})
};
I call it like this:
$.webApi("POST", "http://url", {object:data});
Makes everything nice and simple. And I don't have to remember all the settings every time.
I have an ASP.Net MVC 3 application that uses a jQuery .ajax call to POST to a server-side controller action as follows
Client-Side jQuery call:
//Page the server
$.ajax({
url: '/Home/Call_Abort',
type: 'POST',
data: "{ 'op_id': '" + ajaxOPID + "', 'statMsg': '" + ajaxStatMsg + "'}",
contentType: 'application/json; charset=utf-8',
success: function (data) {
window.location.href = data.redirectUrl;
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error while paging the server to abort. Reported error: '" + xhr.responseText + "'.");
}
});
Server-controller action:
[HttpPost]
public JsonResult Call_Abort(string op_id, string statMsg)
{
return Json(new
{
redirectUrl = Url.Action("Operator_Home", "Home", new { op_id = op_id, status = statMsg }),
isRedirect = true
});
}
The return URL is supposed to redirect the user to a different View (i.e. the Operator_Home View). This works on my local development PC, routing to the Operator_Home View as expected, but when I run it on my Development Web Server (Server 2008 with IIS 7) to test, I get the following 404 error page thrown as the xhr.responseText result in the .ajax call above.
It seems like what's happening is instead of redirecting to the View I specify in the redirectURL (i.e. Operator_Home), it seems to think the Call_Abort controller action is supposed to return a Call_Abort View, since no such View exists the error below gets tossed. But why would this happen on the Web Server and not on my local PC running the Visual Studio dev server? Is there some setting I need to make adjust for my application on IIS in order to get it to behave as it does on my development machine. My understanding of MVC routing isn't clear enough to know why this is occurring. Any help or insight is appreciated.
UPDATE
My apologies, there are several servers I'm working with at my place of employemnt, I was referencing the wrong web server. The server I'm running this on is Server 2008 with IIS7
The error turned out to be an issue with the URL in tha .Ajax call I modified the URL as follows:
//Page the server
var abortURL = window.location.origin + '/myApp/Home/Call_Abort';
$.ajax({
url: abortURL,
type: 'POST',
data: "{ 'op_id': '" + ajaxOPID + "', 'statMsg': '" + ajaxStatMsg + "'}",
contentType: 'application/json; charset=utf-8',
success: function (data) {
window.location.href = data.redirectUrl;
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error while paging the server to abort. Reported error: '" + xhr.responseText + "'.");
}
});
This resolved the issue and allowed jQuery to complete the POST.
I have the following jQuery ajax request in a .js file:
$.ajax({
type: "GET",
url: "Download.aspx/ZipCheck",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
The request fails and an alert pops up that says "200 OK". However, if I change the ajax request type to "POST" then it works and I have an alert that pops up with the expected data being returned from Download.aspx/ZipCheck.
Why does the GET fail, and why does the POST succeed? My understanding must be flawed about the difference between the two, because I thought that a GET request still would return something from the server.
WebMethods are by default restricted to POST, you need to explicitly enable the GET request, for example using UseHttpGet on the ScriptAttribute, like this:
[WebMethod, ScriptMethod(UseHttpGet=true)]
public thing ZipCheck() {
//return object
}
I am doing a simple $.ajax request:
$.ajax({
type: "POST",
url: "/Run/" + param1 + "/" + param2,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
If my param2 value is like http://localhost/pub/file?val1=Some Text&val2=Some Text then encoding done using escape(param2), encodeURI(param2), encodeURIComponent(param2) doesn't help. And I get following ERROR -->
HTTP Error 400.0 - Bad Request
ASP.NET detected invalid characters in the URL
My Questions -->
How should I encode param2 ?
What is the maximum length of request URL in $.ajax call ?
Is request URL max length dependent on type of browser from which request is made ?
I have observed that if I use Ajax.ActionLink then I do not need to encode the parameters passed to action and I can pass parameters with length > 10,000 characters as well. But I do not know how to make an explicit call using Ajax.ActionLink from my java script. I need to click on that actionlink to make call through Ajax.ActionLink.
Benefits of Ajax.actionLink-->
Please see the length of parameter categoryName passed to action using Ajax.ActionLink (This is mine observation)
Such big parameters should be posted and not sent in the URL.
$.ajax({
type: 'POST',
url: '/Run',
data: { param1: param1, param2: param2 },
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
This will automatically handle parameter encoding. If you absolutely insist on sending them in the url you may declare a global javascript variable that will hold the url to call:
<script type="text/javascript">
var url = '<%= Url.Action("Run"), new { param1 = "value1", param2 = "value2" } %>';
$(function() {
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
error: function(error) {
},
success: function(html) {
}
});
});
</script>
There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:
$.post("/Journal/SaveEntry", JSONstring);
And here is the ajax method I tried:
$.ajax({
url: "/Journal/SaveEntry",
type: "POST",
data: JSONstring
});
Here is my Controller:
public void SaveEntry(string data)
{
string somethingElse = data;
}
For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?
Thanks very much.
UPDATE: It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:
$.post("/Journal/SaveEntry", { "jsonData": JSONstring });
Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:
public void SaveEntry(string jsonData)
and my post action in JS looks like:
$.post("/Journal/SaveEntry", { jsonData: JSONstring });
JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:
JSONstring = JSON.stringify(journalEntry); // journalEntry is my JSON object
So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.
Final Answer:
It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.
Actually, make sure youre using the
right key name that your serverside
code is looking for as well as per
Olek's example - ie. if youre code is
looking for the variable data then you
need to use data as your key. –
prodigitalson 6 hours ago
#prodigitalson, that worked. The
variable names weren't lining up. Will
you post a second answer so I can
accept it? Thanks. – Mega Matt 6 hours
ago
So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.
the data argument has to be key value pair
$.post("/Journal/SaveEntry", {"JSONString": JSONstring});
It seems dataType is missed. You may also set contentType just in case. Would you try this version?
$.ajax({
url: '/Journal/SaveEntry',
type: 'POST',
data: JSONstring,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
Cheers.
Thanks for answer this solve my nightmare.
My grid
..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();
<script type="text/javascript">
function onRowSelected(e) {
id = e.row.cells[0].innerHTML;
$.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
}
</script>
my controller
public ActionResult GridSelectionCommand(string id)
{
//Here i do what ever i need to do
}
The Way is here.
If you want specify
dataType: 'json'
Then use,
$('#ddlIssueType').change(function () {
var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlStoreLocation').get(0).options.length = 0;
$('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you do not specify
dataType: 'json'
Then use
$('#ddlItemType').change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("IssueTypeList", "SalesDept")',
data: { itemTypeId: this.value },
cache: false,
success: function (data) {
$('#ddlIssueType').get(0).options.length = 0;
$('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you want specify
dataType: 'json' and contentType: 'application/json; charset=utf-8'
Then Use
$.ajax({
type: 'POST',
url: '#Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlAvailAbleItemSerials').get(0).options.length = 0;
$('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again.");
}
});
If you still can't get it to work, try checking the page URL you are calling the $.post from.
In my case I was calling this method from localhost:61965/Example and my code was:
$.post('Api/Example/New', { jsonData: jsonData });
Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.