function is taking Null value by ajax in mvc5 - c#

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');
}
});
});

Related

ajax pass a list of int to asp net api controller, parameter is null

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");
}
});

Web API is not working when calling through C# or jQuery ajax

Going crazy. The first call sets the session and the 2nd call gets the session. First 'Post' call return username and session id correctly but when I try to get the session, it returns blank with status code 200.
The same is the case with HttpClient (C#) code.
Both the call works perfectly if I try to set through browser or PostMan.
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session?username=xxxx&password=xxxx",
type: 'POST',
dataType: 'application/json',
success: function (result) {
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session",
type: 'Get',
dataType: 'application/json',
crossDomain: true,
success: function (result) {
debugger;
},
error: function (result) {
debugger;
}
});
},
error: function (result) {
debugger;
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session",
type: 'Get',
dataType: 'application/json',
crossDomain: true,
success: function (result) {
debugger
},
error: function (result) {
debugger;
}
});
}
});
The Get Request from Post Man
{"sessionId":"088BE3296B8778948F649A6B7B8C064B","userName":"user1"}
Am I missing anything?
Do note that Web-APIs are exposed by third party.
The problem is you have used the post method and trying to pass the data in query string.
function DoLogin() {
if (document.getElementById("Email").value == "" && document.getElementById("Password").value == "") {
document.getElementById("Email").focus();
toastr.error("Please enter email and password.");
}
else if (document.getElementById("Email").value == "") {
document.getElementById("Email").focus();
toastr.error("Please enter valid email address.");
}
else if (document.getElementById("Password").value == "") {
document.getElementById("Password").focus();
toastr.error("Please enter valid password.");
}
else {
document.getElementById("ButtonLogin").value = "Validating your account...";
document.getElementById("ButtonLogin").disabled = true;
var model = {
Email: $('#Email').val(),
Password: $('#Password').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "#Url.Action("Login", "Account", null)",
contentType: "application/json"
}).success(function (res) {
var Type = res.type;
if (Type == "error") {
toastr.error(res.value);
document.getElementById("ButtonLogin").value = "login";
document.getElementById("ButtonLogin").disabled = false;
}
else {
window.location.href = res.returnUrl;
}
});
}
}
Usually, in the response for the POST request, there will be a Set-Cookie header.
You may need to pass the cookie in the GET request.

Ajax not hitting controller method

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"

Object obect error on jquery ajax request on dropdown change?

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.

Jquery Ajax call in asp.net Progress Bar update

I am doing jquery ajax call in asp.net, I am getting some value from database in a textbox and on base of it I am making jquery progressbar.
Its getting value in textbox, but its not taking value of progress bar first time, I have to reload the page for value of progress bar.
Below is my code
$(function () {
GetValue();
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
});
function GetValue() {
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
$("#txtcount").val(Result.d);
},
error: function () { alert('error'); }
});
}
[System.Web.Services.WebMethod()]
public static string GetCount()
{
//Get values from DB and return it
}
I also tried with document.ready but no luck, Which event of Jquery should I use to make my progress bar on first time.
try this:
async:false, add to ajax call
$(document).ready(function(){
GetValue();
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
});
})
function GetValue() {
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:false,
success: function (Result) {
$("#txtcount").val(Result.d);
},
error: function () { alert('error'); }
});
}
ajax means Asynchronous, that said, means that you need wait untill your first request suceed, and after pocess with value.
Some pseudocode:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
$("#txtcount").val(Result.d);
//HERE ASSIGN TO PROGRESS BAR
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
// --------------------------
},
error: function () { alert('error'); }
});

Categories