Link inside Link web method - c#

Hi i am trying to navigate through anchor link. Only the first link works. For example if i click a link in a page it goes to that link, but when there is another link in page whcih i have clicked it doesnt work. And also the second has the same class 1st link Please help.
$('#frmDisplay').on('load', function () {
$('#frmDisplay a.anchorLink').on('click', function () {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
public static string getlink(int Id)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString);
string link = "extlink";
BookTree obj = new BookTree();
DataSet ds = obj.getlink(Id);
SqlCommand cmd=new SqlCommand("select vcFilePath from tblBookNodes where iModuleId='" + Id + "'",conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
bytes = (byte[])dr["vcFilePath"];
}
string fileName = link.Replace(" ", "_") + ".htm";
// DirectoryInfo strPath = new DirectoryInfo(HttpContext.Current.Server.MapPath(#"~/Linking/"));
//string strPath = HttpContext.Current.Server.MapPath(#"/Linking/") + fileName;
//foreach (FileInfo file in strPath.GetFiles())
//{
// file.Delete();
//}
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/htmlFile/"), fileName);
var doc = new HtmlDocument();
string html = Encoding.UTF8.GetString(bytes);
doc.LoadHtml(html);
StringWriter sw = new StringWriter();
var hw = new HtmlTextWriter(sw);
StreamWriter sWriter = new StreamWriter(path);
sWriter.Write(sw.ToString());
doc.Save(sWriter);
sWriter.Close();
//string fileContents = html;
//System.IO.File.WriteAllText(path, html);
return File.ReadAllText(path);
}

You have to use "on" instead of find() and event listener attach.
Please refer to this example:
$('#formDisplay a.anchroLink').on('click', function() {
// TODO: handle the click
})
This is necessary because when you add the event listener the DOM is not yet ready to handle requests for non existing content. Using "on" you can attach an event to a class or a simple DOM query.
To be more clear I post your code with modifications based on my previous suggestion:
$('#frmDisplay a.anchorLink').on('click', function () {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d)
},
error: function (response) {
alert(response.responseText);
}
});
});
My last answer (I don't know you were using iFrames):
function clickHandler() {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d);
// You can reload the event handler because the prev one
// has been lost after refreshing the page with the ajax call.
$('#frmDisplay').contents()
.find('a.anchorLink')
.click(clickHandler);
},
error: function (response) {
alert(response.responseText);
}
});
}
$('#frmDisplay').on('load', function () {
$('#frmDisplay')
.contents()
.find('a.anchorLink')
.on('click', clickHandler);
})

Related

Auto map JSON AJAX returned data to table row in Jquery/JavaScript

Ok I have created a tab with a table inside of it as follows -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST", url: "../WebMethods/MarketPersuitMethods.aspx/GetColumnHeaders",
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$tbody.append("<th>" + value.ColumnsName + "</th>");
});
$tbody.append('<tr />').children('tr:last')
setTimeout(function () {
}, 1000);
}
});
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
//$table.appendTo('#TabbedMktList');
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
Here is my C# Code
[WebMethod(EnableSession = true)]
public static string GetQueryInfo()
{
String daresult = null;
DataTable yourDatable = new DataTable();
string strConnString = WebConfigurationManager.ConnectionStrings["TimeClock"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandText = "select * from OCI_TEXT_PROJECT_MASTER where proj_id=2049";
da.SelectCommand = cmd;
cmd.CommandTimeout = 30;
cmd.Connection = con;
con.Open();
da.Fill(yourDatable);
daresult = DataSetToJSON(yourDatable);
return daresult;
}
public static string DataSetToJSON(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table);
return JSONString;
}
It is creating the column headers as I wish for it to do. However, I need to populate all the JSON data for the rows below it. I would not know the column headers as they can change.
I am able to see my results are coming back in JSON data -
[{"Project ID":"18180","OPRN":null,"Proj_Type":"2049","Client Name":null,"client_id":null,"ClientContact":null,"Contact_ID":null,"PN":null,"CompleteDate":"2020-05-21T00:00:00","cost":null,"SQFT":2000,"BIM":null,"LEED":"NO ","Delivery_Meth":"Corey ","City":"Orlando","State":"FL ","County":"Orange","IT":"1141","Project Name":null,"Address":"1234. Orlando Ave","zip":"12345","notes":"<p class=\"MsoNormal\"><b>EXTRA TESTING 1-2-3-43</b></p>","PM":"1141","OLDOWNER":null,"Owner_Contact":null,"ProjectManager":"Corey ","Architect":"Collier Health Services","ContractorORG":"BVW Development","ArchitectID":929,"PNAME":"OCI DYNAMICS CRM PROJECT MANAGEMENT SOFTWARE","PROJ_ID":2049,"Office":"Maitland","MPROJECT":null,"Contractor":930,"addr2":"","PROJSTATUS":2,"TotalProjectTime":null,"corp":"0","ProjectStatus":"Construction","TotalDesignTime":null,"OFFNUM":1,"Owner":null,"ProjectType":null,"MarketSector":"FINANCIAL","users":"1141","team":null,"BuildingType":null,"ETA":null,"designstartdate":null,"FINALCONTRUCT":24000.0000,"ESTCONSTRUCT":15000.0000,"Units":"12","WebType":"P","RequestedBy":null,"RequestedDate":null,"Status":"Interview","RFPDATE":null,"SENTDATE":null,"InterviewDate":null,"OCIDATE":null,"Method":null,"ContractType":"0","ContractName":null,"Tags":"CRM FINANCIAL NewTest rigtest2","TotalProfit/Loss":3,"Disciplines":"Mechanical, CAD, Clerical, QA/QC, Project Management","ChillerType":"1","Revit":"2017","Tons":145,"Rooms":5}]
However -
I have no idea where to get it to map over automatically.
I would ideally think somehow to map it based on the TH header text because they would be the same.
My issue is somewhere in here
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
Figured it out -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (d) {
var data = $.parseJSON(d.d);
var colHeader = Object.keys(data[0]);
for (var i = 0; i < colHeader.length; i++) {
$tbody.append("<th>" + colHeader[i] + "</th>");
}
//sets new line
$tbody.append('<tr />').children('tr:last')
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < colHeader.length; j++) {
$tbody.append('<td>' + data[i][colHeader[j]] + '</td>');
}
$tbody.append('<tr />').children('tr:last')
}
setTimeout(function () {
}, 1000);
}
});
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}

can't redirect method from ajax method to aspx.cs page

I have following code in my CenterDetail.aspx page
function myFunction(id) {
console.log(2);
var myindex = window.ContentPlaceHolder1_ddCountryId.selectedIndex;
console.log(myindex);
var selectedName = window.ContentPlaceHolder1_ddCountryId.options[myindex].text;
console.log(selectedName);
var loc = window.location.href;
console.log(loc);
$.ajax({
type: "POST",
url: loc + "/BindState",
data: { id : id },
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
and following method is in my code behind file.
[WebMethod]
public static string BindState(int id)
{
var states = new StateProvinceCollection().Where(StateProvince.Columns.CountryId = Convert.ToString(id), true).ToList();
string tag = "<select id='StateProvinceId' name='StateProvinceName'>";
tag += "<option value=''>select</option>";
foreach (var item in states)
{
tag += "<option value='" + item.StateProvinceId + "'>" + item.StateProvinceName + "</option>";
}
tag += "</select>";
return tag;
}
everything is still it show http://musicclass/Account/Management/Center/CenterDetail.aspx/BindState 404 not found error.

JSON Invalide primitive

I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}
When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}

Populate items in dropdownlist

I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},

Pass paramater to webservice on ajax

I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',

Categories

Resources