This is my Jquery:
$("#completeMe").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Main.aspx/GetAutocomplete",
type: "POST",
dataType: "json",
data: Data,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return { value: item };
}))
}
})
}
});
This is my Main.aspx.cs:
[System.Web.Services.WebMethod]
public static List<string> GetAutocomplete(string cityName)
{
List<string> City = new List<string>() { "hh", "hh1" };
return City;
}
Now this works when i return string instead of List. But when I use it like this with List I get:
Uncaught TypeError: undefined is not a function jquery-ui.min.js:9...
I don't understand, this solution seem to work to many people on web, maybe it has something to do with my jquery/ui versions? I am using jquery 1.7.1.min and jquery-ui latest version.
Change your success function like this
success: function (data) {
response($.map(data.d, function (item) {
return { value: item };
}))
Data is contained in data.d property.
Related
I want to pass a list of int ids into my controller, but when the data hits the controller action, the parameter is null
[HttpGet]
public async Task<ActionResult> GetReport(int[] items)
{
var viewModel = await _reportLogic.GetReportByIdAsync(items);
// return something;
}
I have this code in my front end
$('#testPreviewList').click(function (e) {
var items = new Array();
$('.reportId').each(function () {
items.push(this.id);
});
console.log(items);
$.ajax({
url: "/home/GetReport",
type: "GET",
//contentType: "application/json; charset=utf-8",
data: { "items": items},
dataType: "json",
success: function (data) {
//do something
});
$("#datos").html(row);
$('#authorNameTextBox').val('');
},
error: function (result) {
//alert("Error");
}
});
});
What am I doing wrong?
thank you
Use POST instead of GET.
Use Traditional property in ajax, set to true.
$.ajax({
url: "/home/GetReport",
type: "POST",
//contentType: "application/json; charset=utf-8",
data: { "items": items},
dataType: "json",
Traditional: true,
success: function (data) {
//do something
});
$("#datos").html(row);
$('#authorNameTextBox').val('');
},
error: function (result) {
//alert("Error");
}
});
I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.
Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
Change the url to this:
url: "../Client/ShowClient"
This ajax is calling from .cshtml file to controller but getValue function is taking Null value on load, but afterwards it works fine. It evens shows the value on alert on ajax call, but getting null on controller. Any help would be highly appreciated.
<script>
$(document).ready(function(){
//get value from dropdown list
var ID = $('#cmb').val();
// ID is taking value
$.ajax({
// /ControllerName/FunctionName
// /Home/getvalue
url: "/Home/getValue",
type: "POST",
// ID is getting from dropdownList
// parameterName/value
data: JSON.stringify({'_ID':ID}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
</script>
[HttpPost]
public JsonResult getValue(string _ID)
{
string a = _ID;
}
It is reasonable that you are taking null on the load, since the value of HTML element with id cmd would be undefined, since I assume that there isn't any value that is selected (option of a select element has an attribute called selected, when you have selected a value this attribute has the value true).
The strange thing is that you say that afterwards works as it is expected. I doubt this, except if you have any other code that you haven't include it in your post. As it seems there is only an AJAX call after the successfull load of the DOM.
Usually we register to an event, when we make an AJAX call like this. I could assume that you could register to the onChange event of the value of select element (dropdown)
$(document).ready(function(){
$("#cmb").on("change", function(){
//get value from dropdown list
var ID = $(this).val();
// ID is taking value
$.ajax({
// /ControllerName/FunctionName
// /Home/getvalue
url: "/Home/getValue",
type: "POST",
// ID is getting from dropdownList
// parameterName/value
data: JSON.stringify({'_ID':ID}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
});
You have to change your URL and parameter check below code for that :
$(document).ready(function(){
//get value from dropdown list
var ID = $('#cmb').val();
// ID is taking value
$.ajax({
url: "/Home/getValue?_ID=" + ID,
type: "POST",
dataType: "json",
data: 'json',
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
Cheers !!
Change Paramaters Name
use id in replace of _ID
[HttpPost]
public JsonResult getValue(string id)
{
string a = id;
}
$(document).ready(function(){
$("#cmb").on("change", function(){
//get value from dropdown list
var id= $(this).val();
// ID is taking value
$.ajax({
// /ControllerName/FunctionName
// /Home/getvalue
url: "/Home/getValue",
type: "POST",
// ID is getting from dropdownList
// parameterName/value
data: JSON.stringify({'id':ID}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
});
if you are sure that your ID is not null then just try this.
<script>
$(document).ready(function(){
var ID = $('#cmb').val();
$.ajax({
url: "/Home/getValue",
type: "POST",
data: {_ID:ID},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
I am using json result to populate the textbox and I can see the values are returned to Razor view using alert. But I am unable to bind them to textbox.
in my layout.cshtml i am loading the jquery files.
![This is in the header section of my layout page][1]
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/jquery-ui")
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/Site")
This is my index file,
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
any help is greatly appreciated.
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
async : false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
try the async:false in ajax
You haven't posted your data response, but if it is an array of strings, the following should do it.
success: function (data) {
response(data);
},
Since you've already provided the data in the format that it needs (a label and a value), you don't have to map the data. Just pass it directly into the response.
I'm using jquery ajax on dropdown change function.The problem is that even before hitting the url mentioned in the ajax request I'm getting Object object error.
The ajax request is as follows
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: "{ 'Location': '" + locationNo + "'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
The server side code is as follows
[WebMethod]
public static string GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sjson=jSearializer.Serialize(lstCashSafeSelect);
return sjson;
}
I've checked the string sjson and the data is returning correctly in json format.
Since the error is showing even before the url is hit,i'm confused on how to proceed further.
Any help will be appreciated.
Change the data like this
data: JSON.stringify({ 'Location': locationNo }),
Then your code will look like
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: JSON.stringify({ 'Location': locationNo }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
Edit
Since your dataType is json, you should return json, not string. Change your server side code like this,
[WebMethod]
public static List<CashSafeSelect> GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
return lstCashSafeSelect;
}
You dont have to serialize those lists
Issue solved,Thanks to every one who replied especially #Anoop.
Issue was that I've set Autopostback=true for the dropdown where the ajax call is made.I've removed the autopostback property of the dropdown and now the code is working fine.
I wonder how a fresh day,clear mind helps to solve the issues.