Refresh and Clear button aren't working on asp.net application - javascript

My 'Clear' and 'Refresh' buttons do not clear out my Branch and Terminal inputs on my webpage. I think it has something to do with my KnockoutJS since I bind the data to a table in the DB. Perhaps the KnockoutJS thing isn't functioning properly. The page is supposed to display the fetched data from the DB everytime 'Refresh' button is clicked too. But it seems like the code doesn't even fetch anything from the DB.
I'm new to learning the framework of asp.net so can anyone pls help me w my issue? T
I tried to look at other API functions and only tweaked a little parameters to fetch from the DB since there are different tables I need to fetch from. I also modified the Stored Procedure of the respective page for the API function to grab the data from SQL Server but still the page appears blank and the buttons aren't working.
buttons html
<div class="col-sm-5 col-md-5 col-lg-5 m-b-15">
<button id="btnRefreshForecastDetails" type="button" class="btn btn-primary btn-custom w-md waves-effect waves-light" data-bind="click: refresh"><i class="mdi mdi-refresh"></i> <span>Refresh</span></button>
<button id="btnClearAll" type="button" class="btn btn-primary btn-custom w-md waves-effect waves-light" onclick="ClearAll();"><i class="mdi mdi-close"></i> <span>Clear All</span></button>
</div>
.JS function
var ObservableModelMain = function () {
var self = this;
self.gifts = ko.observableArray();
self.refresh = function () {
StartLoadingPage();
url = sessionStorage.getItem('WebApiURL') + "IT_GetDetails?ID=" + sessionStorage.getItem('ID');
var table = $('#main-table');//table from DB
var PageSize = sessionStorage.getItem('PageSize');
var valueToPush = {};
var FinalData = [];
valueToPush.PageNumber = table.getPageNum();
valueToPush.PageSize = PageSize;
valueToPush.SortExpression = table.getSortExpression();
valueToPush.SortOrder = table.getSortOrder();
valueToPush.SearchBranchNo = _strSearchBranchNo;
valueToPush.SearchTerminalNo = _strSearchTerminalNo;
valueToPush.SearchDate = _strSearchDate;
FinalData.push(valueToPush);
valueToPush = {};
var myJSON = JSON.stringify(FinalData)
$.ajax({
url: url,
type: "POST",
data: myJSON,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
DeviceStatus = data["errorCode"];
Param = data["param"];
if (DeviceStatus == 'SUCCESS') {
var obj = JSON.parse(Param);
if (obj[0].length == 0 && obj[1][0].TotalOutput != 0) {
document.getElementById('btnRefreshForecastDetails').click();
}
else {
self.gifts(obj[0]);
}
table.updateTable(parseInt(PageSize), obj[1][0].TotalOutput);
//GetBranchList();
}
else {
swal("Error", "Fail to retrieve forecast details, " + Param, "error");
}
CloseLoadingPage();
}
});
}
};
API function
public async Task<TCR_RESPONSEMESSAGE> IT_GetForecastDetails(ITForecast[] Alldata)
{
StringBuilder sbReturnMessage = new StringBuilder();
StringBuilder sbTraceMessage = new StringBuilder();
API_COMPLETEMESSAGE tcm = null;
WebAPITraceLog wtl = null;
string reqStr = string.Empty;
string repStr = string.Empty;
string MessageSeqNo = string.Empty;
const string functionNameStr = nameof(IT_GetForecastDetails);
API_FUNCTION APIFunctionCode = API_FUNCTION.IT_GetForecastDetails;
StringBuilder sbSQLStmt = new StringBuilder();
bool asyncResult = false;
DataSet dsData = new DataSet();
bool blnResult = false;
string strTable = "tblForecastDetails";
List<SqlParameter> SqlParameters = new List<SqlParameter>();
try
{
using (SqlConnection SQLDBConn = new SqlConnection(sqlTCRSecureBODBConnStr))
{
await SQLDBConn.OpenAsync();
SqlParameters.Add(new SqlParameter("#PageNumber", Alldata[0].PageNumber));
SqlParameters.Add(new SqlParameter("#PageSize", Alldata[0].PageSize));
SqlParameters.Add(new SqlParameter("#SortExpression", Alldata[0].SortExpression));
SqlParameters.Add(new SqlParameter("#SortOrder", Alldata[0].SortOrder));
SqlParameter OutputParam = new SqlParameter("#TotalRecords", SqlDbType.BigInt);
OutputParam.Direction = ParameterDirection.Output;
SqlParameters.Add(OutputParam);
blnResult = ReadDataSetByStoredProcedure("GetForecastDetailsWithPage", SqlParameters, strTable, DEFAULT_LOG_NAME, SQLDBConn, ref dsData);
if (blnResult == false)
{
tcm = FAIL_READ_MESSAGE;
tcm.Param = "Fail to read GetForecastDetailsWithPage.";
goto ExitHandler;
}
DataTable tbl = new DataTable("tblPagerInfo");
tbl.Columns.Add("TotalOutput", typeof(long));
tbl.Rows.Add(Convert.ToInt64(SqlParameters[4].Value));
dsData.Tables.Add(tbl);
}
if (dsData != null)
{
tcm = SUCCESS_MESSAGE;
tcm.Param = JsonConvert.SerializeObject(dsData.Tables);
goto ExitHandler;
}
else
{
tcm = FAIL_READ_MESSAGE;
tcm.Param = "Fail to read GetForecastDetailsWithPage.";
goto ExitHandler;
}
ExitHandler:
tcm.Function = APIFunctionCode;
return await ProcessAPICompleteMessage(tcm, functionNameStr);
}
catch (Exception ex)
{
string errorMessages = string.Empty;
errorMessages += "Description : " + ex.Message;
LogError(DEFAULT_LOG_PATH, DEFAULT_LOG_NAME, errorMessages, GetLineNumber(ex).ToString(), functionNameStr);
tcm = EXCEPTION_MESSAGE;
tcm.Function = APIFunctionCode;
tcm.Param = errorMessages;
return await ProcessAPICompleteMessage(tcm, functionNameStr);
}
}
I expect for the "Refresh" and "Clear" buttons to work, and for the DB data from the declared table to be fetched to be displayed on the web page.

well, for starters I don't see your knockout anywhere being bound to your viewmodel, preferably below your viewmodel definition.
ko.applyBindings(new ObservableModelMain());
and secondly your clear button has a plain old javascript onclick event attribute, not a data-bind to a -also not available- self.clear = function() {...} in your knockout viewmodel

Related

How can I display 2 real-time value using SignalR in 2 elements ? (ASP.NET MVC)

I followed the video and I can display a real-time value using SignalR in tag. But I don't know what signalr script code do so when I add a similar code to display 2 real-time values in 2 tags , it just displays one. I really hope someone will know clearly about that SignalR and please tell me something's wrong in my project? Thank you so much!
My code in index.html :
<script type="text/javascript">
$(function () {
//Proxy created on the fly
var cus = $.connection.cusHub;
//Declare a function on the job hub so the server can invoke
cus.client.displayValue = function () {
getData();
getData1();
};
//Start the connection
$.connection.hub.start();
getData();
getData1();
});
function getData() {
var $tbl = $('#tblValue');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
model.Value
);
});
}
});
}
function getData1() {
var $tbl = $('#tblValue1');
$.ajax({
url: $("#Get1").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus1, function (i1, model) {
$tbl.append
(
model.Value
);
});
}
});
}
</script>
Tag h2 with id="tblValue"> runs and has its value but not with id="tblValue1" :
<div class="col-md-6 col-lg-3">
<div class="statistic__item statistic__item--orange">
<h2 id="tblValue" class="number">
</h2>
<span class="desc">MONTHLY COST</span>
<div class="icon">
<i class="zmdi zmdi-money"></i>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3">
<div class="statistic__item statistic__item--blue">
<h2 id="tblValue1" class="number">1,086</h2>
<span class="desc">YEARLY USAGE</span>
<div class="icon">
<i class="zmdi zmdi-time"></i>
</div>
</div>
</div>
My code in Controller ( I just copy paste from function JsonResult Get ) :
public JsonResult Get()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ValueConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand value1 = new SqlCommand(#"SELECT [DeviceID],[Value] FROM [dbo].[Device1] WHERE [DeviceID]='PM1'", connection))
{
value1.Notification = null;
SqlDependency dependency = new SqlDependency(value1);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = value1.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
DeviceID = (string)x["DeviceID"],
Value = (double)x["Value"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
public JsonResult Get1()
{
using (var connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ValueConnection"].ConnectionString))
{
connection1.Open();
using (SqlCommand value1 = new SqlCommand(#"SELECT [DeviceID],[Value] FROM [dbo].[Device1] WHERE [DeviceID]='PM2'", connection1))
{
value1.Notification = null;
SqlDependency dependency1 = new SqlDependency(value1);
dependency1.OnChange += new OnChangeEventHandler(dependency_OnChange1);
if (connection1.State == ConnectionState.Closed)
connection1.Open();
SqlDataReader reader1 = value1.ExecuteReader();
var listCus1 = reader1.Cast<IDataRecord>()
.Select(x => new
{
DeviceID = (string)x["DeviceID"],
Value = (double)x["Value"],
}).ToList();
return Json(new { listCus1 = listCus1 }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
private void dependency_OnChange1(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
My code in CusHub.cs :
public class CusHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CusHub>();
context.Clients.All.displayValue();
}
}

How to persist data inside div that appended on button click in JSP using JavaScript, Spring Boot?

I have a dropdown list of cities and a button to add city into vendor model. So I want to add selected city name inside div when button clicked each time. For example, I have list of cities in dropdown and suppose I selected Bangalore and when clicked on add button then it should get added inside div and when I refresh the page, div list should be persistence. Which means, when page get reload or refreshed then added city should be displayed inside a div. Currently what I am suffering from is when I reload page then the cities I added after button clicked, gets emptied each time. So I want help regarding this. Any suggestions would be helpful for me.
Below is my api controller code to save selected city into database:
#RequestMapping(value = AkApiUrl.setdeliverycity, method = { RequestMethod.POST, RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> setdeliverycity(HttpServletRequest request, HttpSession session, #RequestParam("delivercityid") String delivercityid,
#RequestParam("vendorid") String vendorid) {
CustomResponse = ResponseFactory.getResponse(request);
try {
User loginuser = (User) session.getAttribute("user");
Long vid = Long.parseLong(vendorid);
User vendor = userDao.findByUserid(vid);
String vendorname = vendor.getName();
Long cid = Long.parseLong(delivercityid);
DeliveryCity city = deliverycityDao.findByDelivercityid(cid);
VendorCity vendorCity = new VendorCity();
vendorCity.setVendorcity(city);
vendorCity.setName(vendorname);
vendorCity.setVendorid(vendor);
vendorCity.setCreatedby(loginuser);
VendorCity delivercity = vendorcitydao.save(vendorCity);
if (delivercity != null) {
CustomResponse.setResponse(delivercity);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
CustomResponse.setResponseMessage(CustomStatus.SuccessMsg);
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
Below is script for button click to add cities into div when Ajax success:
function addcity(){
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
var url = "../api/setdeliverycity";
$.post(url,{
delivercityid : delivercityid,
vendorid : vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
var vid = vendor.vendorcityid;
var city = vendor.vendorcity.city;
var citydiv = "";
var cityid = vendor.vendorcity.delivercityid;
var citylistlength = city.length;
if(citylistlength > 0) {
citydiv = citydiv+"<div>"+city+" <i class=\"fa fa-times\" onclick=\"removecity('"+cityid+"')\"></i></div>";
}else{
citydiv = citydiv+"<div style=\"text-align: center; float: left; margin-left: 40%; font-size: medium; font-weight: bolder; background: blanchedalmond;\"><span>Choose city from list</span></div>";
}
$('#citydivid').append(citydiv);
$('#cid').val(cityid);
$('#vendorcityid').val(vid);
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
You can check on page load if there is any data inside your localStorage or not .If yes you can get that datas and call your ajax to execute further codes and inside this ajax call if data are successfully appended inside your DOM your can clear previous data and save new data i.e : vendorid..etc inside localStorage.
Here , is sample code which should work :
$(function() {
//check if the localStorage is not null
if (localStorage.getItem("delivercityid") != null) {
var delivercityid = localStorage.getItem("delivercityid"); //get that value
var vendorid = localStorage.getItem("vendorid");
ajax_call(vendorid, delivercityid); //call function
localStorage.clear(); //clear from here after page load..
}
});
function addcity() {
var vendorid = document.getElementById('vendordeliveryid').value;
var delivercityid = document.getElementById('vendorcitydd').value;
ajax_call(vendorid, delivercityid)
}
function ajax_call(vendorid, delivercityid) {
var url = "../api/setdeliverycity";
$.post(url, {
delivercityid: delivercityid,
vendorid: vendorid,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
console.log(data.response);
var vendor = data.response;
//..
//other codes..
localStorage.setItem("vendorid", vendorid);
var delivercityid_datas = JSON.parse(localStorage.getItem("delivercityid")) || []; //all datas
delivercityid_datas.push(delivercityid); //push new data inside localstorage
localStorage.setItem("delivercityid", JSON.stringify(delivercityid_datas)); //reinitalze again
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}

Why I cannot open a CSV file using JQuery and FileContentResult

I'm trying to make an ajax call (I specifically don't want to do it using ActionLink).
I'm having a controller that is like this:
public IActionResult ExportUsers(List<string> listOfEmails)
{
/*some data processing*/
return File(result, "text/csv", "ExportCandidates.csv");
}
On the other side with ajax I do this simple call:
$.ajax({
url: '/Admin/Testcenter/GenerateInvitationPreview',
type: 'post',
data: {
//some input data to send to the controller ​
​},
​success: function (response) {
​)
​}
​});
I know there exists something for pdf files where you return a base64 file and with the response in the ajax call you just write something like pdfWindow.document.write(...) and this will open a new window with a pdf file.
Is there a way to extract the response for my CSV file and generate it so the user downloads it ?
USE NPOI Library for Excel Sheet Generation
//Generate Excel Sheet
try
{
Guid gid = Guid.NewGuid();
string ext = ".xls";
string[] Headers = { "Appointments Id", "Date of Appointment", "Doctor Name", "Patient Name", "Visit Type", "Status" };
string fileName = "AppointmentsExcelSheet_" + gid.ToString() + ext;
var serverpath = _env.ContentRootPath;
string rootpath = serverpath + "/wwwroot/ExcelSheets/" + fileName;
FileInfo file = new FileInfo(Path.Combine(rootpath, fileName));
var memorystream = new MemoryStream();
using (var fs = new FileStream(rootpath, FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Appointments List");
IRow row = excelSheet.CreateRow(0);
var font = workbook.CreateFont();
font.FontHeightInPoints = 11;
font.FontName = "Calibri";
font.Boldweight = (short)FontBoldWeight.Bold;
for (var i = 0; i < Headers.Length; i++)
{
var cell = row.CreateCell(i);
cell.SetCellValue(Headers[i]);
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(font);
}
var result = _Appointment.GetAppoinmentsPDf();
int index = 1;
foreach (var app in result.Items)
{
//var PatientDob = Convert.ToDouble(app.PatientDOB);
row = excelSheet.CreateRow(index);
row.CreateCell(0).SetCellValue(app.AppointmentId);
row.CreateCell(1).SetCellValue(app.DateofAppointment+" "+app.TimeofAppointment);
row.CreateCell(2).SetCellValue(app.DoctorFullName);
row.CreateCell(3).SetCellValue(app.SelectedPatientName);
row.CreateCell(4).SetCellValue(app.PurposeofVisit);
if (app.IsActive == false)
{
row.CreateCell(5).SetCellValue("Inactive");
}
else
{
row.CreateCell(5).SetCellValue("Active");
}
index++;
}
workbook.Write(fs);
}
using (var filestream = new FileStream(rootpath, FileMode.Open))
{
filestream.CopyToAsync(memorystream);
}
memorystream.Position = 0;
//send filepath to JQuery function
response.Msg = "/ExcelSheets/" + fileName;
}
catch (Exception Ex)
{
//exception code
}
return Ok(reponse.Msg)
//JavaScript
function AppointmentsExcelSheet() {
//var token = Token;
//var link = path;
debugger
$.ajax({
//'Content-Type': 'application/pdf.',
type: "GET",
url: "/api/Appointments/GetAppointmentsExcelSheet",
beforeSend: function () {
$.blockUI({
message: ('<img src="/images/FadingLines.gif"/>'),
css: {
backgroundColor: 'none',
border: '0',
'z-index': 'auto'
}
});
},
complete: function () {
$.unblockUI();
},
success: function (data) {
debugger
//downloads your Excel sheet
window.location.href = data.msg;
}
});
}
The best way to do what you want to do is to not use AJAX, but use either a link click that opens a new window (since you are passing in parameters) If you could use a
<form target="_blank">
to open a form response. Inside the form can be a field or fields that contains the list of emails (it can be one field, or multiple input fields with the same name). Your action handler can accept that list, parse it, and return a File response, and the natural result of opening the new window from the form post operation is a file that opens up.

How can I redirect to an action in .Net Core after making an Ajax call?

I have a script that makes an ajax call to an action in the controller and save some records.
The whole process is working fine but my little issue is to redirect to another page after saving records successfully.
With my code below, the records were added successfully with an alert indicating as it is described in the code "msg + "Courses were Registered"". Rather than doing that I want it to redirect to an action.
Javascript code:
<input type="submit" value="Register Courses" id="register" class="btn btn-rose" />
<script>
$(document).ready(function () {
$("#register").click(function () {
var items = [];
$('input:checkbox.checkBox').each(function () {
if ($(this).prop('checked')) {
var item = {};
item.CourseID = $(this).val();
item.CourseCode = $(this).parent().next().html();
item.CourseName = $(this).parent().next().next().html();
item.Units = $(this).parent().next().next().next().html();
items.push(item);
}
});
var options = {};
options.url = "/Course/SaveCourse";
options.type = "POST";
options.dataType = "json";
options.data = JSON.stringify(items);
options.contentType = "application/json; charset=utf-8;";
options.success = function (msg) {
alert(msg + " Courses were Registered");
};
options.error = function () {
alert("Error while Registering Courses");
};
$.ajax(options);
});
});
</script>
Controller
[HttpPost]
public IActionResult SaveCourse([FromBody]List<CourseRegModel> courseIDs)
{
var user = HttpContext.Session.GetString("currentUser");
if (user == null)
{
return RedirectToAction("Login", "Account");
}
ViewBag.student = user;
var pendingPayment = (from row in _context.BursaryTransactions where row.MatricNo == user && row.ResponseCode == "021" select row).Count();
if (pendingPayment > 0)
{
return RedirectToAction("PaymentSummary", "Student");
}
var student = _context.StStudentInfo.Include(m =>m.AdmInstProgramme.AdmInstDepartment).Include(m =>m.AdmInstClassLevels).FirstOrDefault(m => m.MatricNo == user);
var session = _context.AdmInstProgrammeTypeSession.Include(m => m.AdmInstSemesters).Include(m => m.AdmInstSessions).Include(m => m.AdmInstProgramType).Where(m => m.IsActive == true).FirstOrDefault(m => m.ProgramTypeId == student.ProgrammeTypeId);
foreach (CourseRegModel courseID in courseIDs)
{
courseID.Level = student.AdmInstClassLevels.ClassLevel;
courseID.Semester = session.AdmInstSemesters.Semester;
courseID.Session = session.AdmInstSessions.SessionName;
courseID.Department = student.AdmInstProgramme.AdmInstDepartment.Department;
_context.CourseRegModel.Add(courseID);
}
int courses = _context.SaveChanges();
return Json(courses);
}
Objective is to return RedirectToAction("MyCourses","Courses"); after SaveChanges();
If you want to redirect to another action method why would you use AJAX? But I think you can work around that by performing the redirect in the client side AJAX after it is successfully receive a response you use JavaScript to do the redirect
You can simply redirect your page inside ajax's success handler,
options.success = function (msg) {
window.localtion.href = "/Courses/MyCourses";
// or window.location.href = '#url.Action("MyCourses","Courses")';
};

Telerik auto complete box text changed event using Java script

My requirement is I have 2 controls Code and description, when I select the code description will automatically displays and I want to select multiple codes automatically display multiple descriptions in description control and vice versa.
For this scenario I am supposed to use "auto complete box" using page methods, for the first time I am using Telerik controls.
Now I am able to get Codes in code auto complete box and able to select multiple codes.
Now my question is how to select the description after selecting multiple codes using Java script/jQuery?
My code is like below
<telerik:RadAutoCompleteBox ID="RdAutoClassCode" runat="server" Width="150" DropDownHeight="150"
DropDownWidth="150" TokensSettings-AllowTokenEditing="True" OnClientTextChanged="OnClientChange" on>
<WebServiceSettings Method="GetISOCodesRadCombobox" Path="GetClassCodeAndDescription.aspx" />
</telerik:RadAutoCompleteBox>
function OnClientChange() {
debugger;
alert("Hi");
}
Text changed event is not firing using above code.
Please provide any sample for this?
Thanks in advance,
Srividya
I finally got the solution.
<telerik:RadAutoCompleteBox ID="RdAutoClassCode" runat="server" Width="150" DropDownHeight="70"
OnClientEntryRemoved="RemoveEntry" OnClientEntryAdded="addNewEntry" height="150" DropDownWidth="150"
TokensSettings-AllowTokenEditing="True">
<WebServiceSettings Method="GetISOCodesRadCombobox" Path="GetClassCodeAndDescription.aspx" />
</telerik:RadAutoCompleteBox>
<telerik:RadAutoCompleteBox ID="RdAutoClassDesc" runat="server" Width="150" DropDownHeight="70"
height="150" DropDownWidth="150" TokensSettings-AllowTokenEditing="True">
<WebServiceSettings Method="GetISOCodeDescriptionsRadCombobox" Path="GetClassCodeAndDescription.aspx" />
</telerik:RadAutoCompleteBox>
Web Methods:
[WebMethod]
public static AutoCompleteBoxData GetISOCodesRadCombobox(object context)
{
string searchString = ((Dictionary<string, object>)context)["Text"].ToString();
DataTable data = GetData(searchString, 0);
List<AutoCompleteBoxItemData> result = new List<AutoCompleteBoxItemData>();
foreach (DataRow row in data.Rows)
{
AutoCompleteBoxItemData childNode = new AutoCompleteBoxItemData();
childNode.Text = row["CodeNumber"].ToString();
childNode.Value = row["CodeNumber"].ToString();
result.Add(childNode);
}
AutoCompleteBoxData res = new AutoCompleteBoxData();
res.Items = result.ToArray();
return res;
}
[WebMethod]
public static AutoCompleteBoxData GetISOCodeDescriptionsRadCombobox(object context)
{
string searchString = ((Dictionary<string, object>)context)["Text"].ToString();
DataTable data = GetData(searchString, 1);
List<AutoCompleteBoxItemData> result = new List<AutoCompleteBoxItemData>();
foreach (DataRow row in data.Rows)
{
AutoCompleteBoxItemData childNode = new AutoCompleteBoxItemData();
childNode.Text = row["CodeDesc"].ToString();
childNode.Value = row["CodeDesc"].ToString();
result.Add(childNode);
}
AutoCompleteBoxData res = new AutoCompleteBoxData();
res.Items = result.ToArray();
return res;
}
private static DataTable GetData(string text, int Value)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["QMSDBCON"]);
DataSet ds = SqlHelper.ExecuteDataset(con, "usp_GetIsoCode", text, Value);
DataTable data = new DataTable();
// adapter.Fill(data);
data = ds.Tables[0];
return data;
}
JavaScript Calling for new entry:
function addNewEntry() {
debugger;
var autoCompleteBoxCode = $find("<%= RdAutoClassCode.ClientID %>");
var autoCompleteBoxDescription = $find("<%= RdAutoClassDesc.ClientID %>");
var entriesCount = autoCompleteBoxCode.get_entries().get_count();
var entry = new Telerik.Web.UI.AutoCompleteBoxEntry();
autoCompleteBoxDescription.get_entries().clear();
for (var i = 0; i < entriesCount; i++) {
var code = autoCompleteBoxCode.get_entries().getEntry(i).get_text();
_ClassCodeSelectedIndexChanged(code);
}
}
Calling server method using Json
function _ClassCodeSelectedIndexChanged(code) {
debugger;
var URL = window.location.protocol + "//" + window.location.host;
URL = URL + "/GetClassCodeAndDescription.aspx/GetISOCodesRadComboboxData";
$(document).ready(function () {
$.ajax({
type: "POST",
url: URL,
data: "{Code : '" + code + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
onsuccess(msg);
},
error: function (xhr) {
onerror(xhr);
}
});
});
}
jQuery("#textbox").blur(function() {
ajaxFunction(jQuery("#textbox").val());
});
function ajaxFunction(code){
// Your ajax call
}
Try this hopeFully this help.

Categories