Ajax call to webmethod gives ERROR 500 - javascript

I'm a beginner and I want to use ajax to load some data from database to dropdownlist when another dropdownlist selected index in changed
but I'm getting nothing but 500 error
My jquery ajax code
function ddlGroups() {
var s = $("#Content_ddlGroups").find("option:selected").prop("value");
$.ajax({
method: "GET",
contentType: "application/json; charset=utf-8",
//url is the path of our web method (Page name/function name)
url: "../panels/admin/AddProject.aspx/getSubgroups",
data: { Id: s },
dataType: "json",
//called on jquery ajax call success
success: function (result) {
$('#Content_SubGroups').empty();
$.each(result.d, function (key, value) {
$("#Content_ddlGroups").append($("<option></option>").val(value.GroupID).html(value.Title));
});
},
//called on jquery ajax call failure
error: function ajaxError(result) {
alert(result.status + ' : ' + result.statusText);
}
});
};
and my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt());
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}
What is the problem??

The jQuery is not the problem here. The 500 error is thrown by the server, so you should review the log of your c# code to find out the details about it and be able to narrow the causes.

In your AJAX Call actually 500 error caused beacuse you have passed
Id:s instead of Id having some digits. Ex. Id : 5.
I see your code if you passed string as a id so in your server side method
you are trying to convert that string to int.That actually causes the 500 error.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt()); // Here You have convert string to Int that's why you got 500 Error.
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}

Related

IIS connections overload and CPU running high

We have an MVC 5 website hosted by iis on our server but we are experiencing the following problem with one of the functionalities in the website.
We have a datatable that gets populated with data from a SQL database. For each record a checkbox gets created for users to check and link that record. Once the record is checked and linked, that specific record is stored in a link table. Please see the code bellow for this functionality. For each record I call a method on the server side and that executes the stored proc.
javascript
$("#btnLinkTest").click(function () {
var counter = 0;
var checked_checkboxCounter = 0;
$('#counter').text("0 linked");
$('#linkModal').modal('show');
var oTable = $("#StudentListTable").dataTable();
$(".cbxLink:checked", oTable.fnGetNodes()).each(function () {
checked_checkboxCounter = checked_checkboxCounter + 1;
var currentRow = $(this).closest("tr");
var data = $('#StudentListTable').DataTable().row(currentRow).data();
var ER, AC;
var StudentID = data['StudentID'];
var TestID = $('#lblGradeID').html();
var ET = $(this).closest('tr').find(".extraTime").val();
if ($(this).closest('tr').find(".cbxER").is(':checked')) {
ER = "True";
} else {
ER = "False";
}
if ($(this).closest('tr').find(".cbxAC").is(':checked')) {
AC = "True";
} else {
AC = "False";
}
var jsObject =
{
StudentID: StudentID,
TestID: TestID,
ModifiedBy: "1",
ElectronicReader: ER,
Accomodation: AC,
StudentExtraTime: ET
};
$.ajax({
type: "POST",
url: "/Administration/LinkTestToStudent_Ins/",
data: JSON.stringify(jsObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
counter = counter + 1;
$('#counter').text(counter + " / " + checked_checkboxCounter );
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
return false;
});
c#
public string LinkTestToStudent_Ins(string StudentID, string TestID, string ModifiedBy, string ElectronicReader, string Accomodation, string StudentExtraTime)
{
string result;
DataBaseConnection dbConn = new DataBaseConnection();
using (SqlConnection con = dbConn.SqlConn())
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("StudentTestLink_ins", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StudentID", StudentID);
cmd.Parameters.AddWithValue("#TestID", TestID);
cmd.Parameters.AddWithValue("#ModifiedBy", HttpContext.Current.Session["UserID"]);
cmd.ExecuteNonQuery();
con.Close();
return result = "Linked";
}
catch (Exception ex)
{
return "Connection Error";
}
}
}
The problem is if we link over a 100 records for example, the connections on the server goes up a lot (so 100 in this case) and the cpu runs at almost 100% because of the IIS Worker. I suspect that this is happening because the javascript code calls the c# all at once for all checked records.
Please advise how I can optimize this code so that I do not get the above mentioned problem. Possibly I can call the c# method one at a time and not all at once.

Download a file through ajax request in asp.net MVC

I am trying to download file through ajax call in asp.net
my javascript:
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
var strAccountCodes = '';
for (var i = 0; i < data.length; i++) {
strAccountCodes += data[i].AccountCode + ",";
}
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes }
});
my action method:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
return File(output, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
code is executing without any errors but it's not downloading any file.
is that anything i am missing?
You should know that AJAX call is not intended to download CSV file directly. Therefore, you can create a byte array from MemoryStream instance and store it inside Session or TempData variable, then return 'successful' state to enable redirect on AJAX success response:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
// creates byte array from stream
TempData["Output"] = output.ToArray();
// returns successful state
return Json("Success", JsonRequestBehavior.AllowGet);
}
Second, create a controller action with GET method and pass stored byte array from Session or TempData into FileResult:
public ActionResult DownloadCSV()
{
// retrieve byte array here
var array = TempData["Output"] as byte[];
if (array != null)
{
return File(array, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
else
{
return new EmptyResult();
}
}
Finally, handle success response to include location.href which will redirect to controller returning FileResult to download CSV file:
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadCSV", "ControllerName")';
}
}
});
As an option, you could pass CSV file name as parameter from AJAX response using query string.
Related issue:
Creating a byte array from a stream

AJAX call to async method is success, but data returned is undefined

I have a controller, and when I Debug.WriteLine the data which I'm returning it's exactly like it's supposed to be. I'm very new to async in .NET, but it seems something gets lost between the controller and the view, because the AJAX call is a success, but the data which I'm returning is undefined when I try to work with it.
Below is the method in the controller. Here the data is correct, and as far as I know this method works exactly as it should.
[HttpPost]
public async Task<JsonResult> getServerProcesses(string server)
{
HttpClient client = new HttpClient();
QueryPair<JToken, JToken> processes = new QueryPair<JToken, JToken>();
using (client)
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var processesRequest = ProcessURLAsync(baseUrl + "activityMonitor/" + server + "/processes", client);
HttpResponseMessage response = await processesRequest;
var jsonString = response.Content.ReadAsStringAsync().Result;
JObject json = JObject.Parse(jsonString);
var data = json.SelectToken("Processes" + ".Data");
var columns = json.SelectToken("Processes" + ".Columns");
processes.Data = data;
processes.Columns = columns;
Debug.WriteLine(data);
}
return Json(processes);
}
As you can see I use an alert to confirm the success, but when I try something such as getting the length it says it's undefined. Even when I just try to console.log the object it says it's undefined.
$.ajax({
type: 'POST',
url: '/Home/getServerProcesses',
data: {'server': server},
success: function(data) {
console.log("Length: " + data.length);
alert("oui");
$('#server-name').empty();
$('#server-name').append(server);
var dataTable = new google.visualization.DataTable();
for (var i = 0; i < pmdfields.length; i++) dataTable.addColumn('string', pmdfields[i]);
for (var i = 0; i < data.length; i++) dataTable.addRow(data[i]);
var table = new google.visualization.Table(document.getElementById('processTable'));
table.draw(dataTable, {showRowNumber: true, width: '100%', height: '100%'});
},
error: function(data) {
alert('ajax getServerProcesses POST request error');
}
});
From API. Under response it has an empty JSON object full of empty arrays. I suspect the error is in my controller class:

Populate gridview from database using javascript

is there a javascript where I can populate a gridview from the database? For example is there a javascript for this code?
gvRFPCorpCode is the name of my gridview
private void fillCorpCode()
{
DataSet ds = new DataSet();
data.gRowId = this.txtROWID.Text;
ds = data.GetCorpCode();
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
this.gvRFPCorpCode.DataSource = ds.Tables[0];
this.gvRFPCorpCode.DataBind();
}
}
}
ds = data.GetCorpCode(); is equal to this:
public DataSet GetCorpCode()
{
DataSet ds = new DataSet();
SqlParameter[] sqlParam = new SqlParameter[]
{
new SqlParameter("#RowId",sRowId)
};
if (this.InitDataLayerObject() == true)
{
ds = this.ExecuteQuery("dbo.sp_ESS_RFP_GetCorpCode", sqlParam);
}
return ds;
}
It's a stored procedure, here is my stored procedure "dbo.sp_ESS_RFP_GetCorpCode"
ALTER PROCEDURE [dbo].[sp_ESS_RFP_GetCorpCode]
-- Add the parameters for the stored procedure here
#RowId varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #xml as xml
select
#xml =convert(xml,CORPCODE)
from Tbl_ESS_Request_For_Payment_Save
where ROWID=#RowId
select
tbl.col.value('CorpCode[1]', 'varchar(100)') as CorpCode,
tbl.col.value('Amount[1]', 'varchar(100)')as Amount
from #xml.nodes('/NewDataSet/Table1') tbl(col)
END
What I want is to have a javascript equivalent to private void fillCorpCode to populate it on my gridview, BTW, You might ask why I need a javascript if i already have a code in c#, It's because of some process in my program and it is difficult to explain. So please help me on this one, thank you in advance!
do like this
function getJSONData(selVal, callbackName) {
selVal = encodeURI(selVal);
var formdata = { };// any data you want to pass as input
$.ajax({
type: "POST",
url: "aspx",
data: formdata,
cache: false,
success: function (data) {
callbackName(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error in processing data !!' + thrownError);
},
async: false
});
}
function createTable() {
mytable = $('<table Class="table table-striped table-bordered table-hover"></table>').attr({ id: "basicTable" });
// alert(rowData);
var rowobj = JSON.parse(rowData);
// To populate header
var firstrow;
var firstrow = $('<tr></tr>').appendTo(mytable);
$('<td></td>').text('Entity Name').appendTo(firstrow);
$('<td></td>').text('Attribute Name').appendTo(firstrow);
$('<td></td>').text(' Value').appendTo(firstrow);
// To populate rows
$.each(rowobj, function (i, obj) {
$('<td valign="middle"></td>').text(obj.ParentName).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName1).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName2).appendTo(row);});
}
//C# method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static string Mymethod(string entityName, string entityType, string filterValues)
{
List<MasterFields> fields = null;
ServiceWrapper<ILOSService>.Perform(svcClient =>
{
fields = getfields();
});
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(fields);
return output;
}

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources