Is it possible to get javascript data from web to application - javascript

I need to get a list of innerHTML strings from a website (for example facebook) to my .NET application.
Is there a way to get results from the following function into my application (i would put this data into a list) :
var data = new Array();
for(i=0; i<document.getElementsByClassName("class-name").length;i++)
data.push(document.getElementsByClassName("class-name")[i].innerHTML);
The code above outputs exactly the data i need, now my question is if it's possible to somehow get this data into my c# list?
This is how I'd like it to look :
var JS_DATA = data; //get the js array as a variable
static List<string> data = new List<string>(); //make a new list
foreach (string str in JS_DATA)
data.Add(String.Format("{0}", str)); //add the whole js array to the list

Here is an example:
see hidden Field array_store
Client side:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var array_store;
window.onload = function () {
array_store = document.getElementById("array_store");
document.getElementById("array_disp").innerHTML = array_store.value;
};
function UpdateArray() {
var arr;
if (array_store.value == "") {
arr = new Array();
} else {
arr = array_store.value.split(",");
}
arr.push((arr.length + 1).toString());
array_store.value = arr.join(",");
};
</script>
</head>
<body>
<form id="form1" runat="server">
<span id="array_disp"></span>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="UpdateArray()" />
<input type="hidden" id="array_store" name = "ArrayStore" value = '<%=this.ArrayStore %>' />
</form>
</body>
</html>
C#:
protected string ArrayStore = "";
protected void Page_Load(object sender, EventArgs e)
{
this.ArrayStore = Request.Form["ArrayStore"];
}

Related

Why isn't my WebMethod being called from javascript?

I'm working in ASP.Net 4. I have the following within the body tag of my aspx:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"/>
<script type="text/javascript">
function Process() {
var CHK = document.getElementById("<%=lstAffEmployees.ClientID%>");
var checkbox = CHK.getElementsByTagName("input");
var counter = 0;
for (var i = 0; i < checkbox.length; i++) {
if (checkbox[i].checked) {
counter++;
var Attorney = label[i].innerHTML;
var cutoff = Attorney.indexOf('[');
var cAttorney = Attorney.substring(0, cutoff - 1);
PageMethods.saveData(checkbox[i].value, cAttorney);
}
}
return true;
}
</script>
In my code-behind, I have:
[WebMethod]
public static void saveData(string attyNo, string attyName)
{
//mycode
}
In debugging, I get to the PageMethods call in the javascript, but then saveData in my code-behind is never called. I don't understand why not. Can anyone help?

displaying search result of database stored images without file extension

I have an autocomplete search box that culled up the thumbnail of images stored in the database. The problem is that the .jpg extension shows up each times the image name appears in the autocomplete search box. Is there anyway I can modify these codes to prevent the .jpg extension from appearing? Below is my existing code using javascript and ashx.
Thank you in advance!
the aspx:
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete("Search.ashx", {
width: 200,
formatItem: function (data, i, n, value) {
return "<img style = 'width:50px;height:50px' src= 'Images/" + value.split(",")[1] + "'/> " + value.split(",")[0];
},
formatResult: function (data, value) {
return value.split(",")[0];
}
});
});
</script>
<style type="text/css">
.Gridview {
font-family: Verdana;
font-size: 10pt;
font-weight: normal;
color: black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Search here:
<asp:TextBox ID="txtSearch" runat="server" />
<br />
</div>
<div>
<asp:FileUpload ID="fileuploadimages" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
<div>
</div>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</form>
</body>
</html>
the ashx:
public class Search : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string searchText = context.Request.QueryString["q"];
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("select ID,ImageName,ImagePath from ImagesPath where ImageName Like #Search + '%'", connection);
cmd.Parameters.AddWithValue("#Search", searchText);
StringBuilder sb = new StringBuilder();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
sb.Append(string.Format("{0},{1}{2}", dr["ImageName"], dr["ImageName"], Environment.NewLine));
}
}
connection.Close();
context.Response.Write(sb.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
}
Do a search and replace, either in the ashx
dr["ImageName"].ToString().Replace(".jpg", "");
Or in the database
select ID, REPLACE(ImageName, '.jpg', '') AS ImageName, ImagePath from ImagesPath
Or if you have more than one extension, you can also do this
Path.GetFileNameWithoutExtension(dr["ImageName"].ToString())
This filters out the extension of every file, and the path should it be present:
string file = #"c:\folder\testFile.jpg";
string result = Path.GetFileNameWithoutExtension(file);
//result: testFile
Translated to your snippet it would look something like this.
while (dr.Read())
{
string file = Path.GetFileNameWithoutExtension(dr["ImageName"].ToString());
sb.Append(string.Format("{0},{1}{2}", file, file, Environment.NewLine));
}

document.getElementById('button2').click(); not working

I am try to automatically fire a sub routine with with a javascript "document.getElementById('button2').click();" as it is in the below code. Can someone please help me see why the code is not working. Thank you
<%# Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" debug = "true"%>
<%# Import Namespace="System.Data.SqlClient"%>
<%# Import Namespace="System.Data"%>
<script language="vb" runat="server">
Sub sendmsg(sender As Object, e As EventArgs)
response.Redirect("index.aspx")
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function Confirm() {
var str = $('#loutput').val(); //'We are inviting you for s special business meeting on Tueday, at No 12, Fred street. for more information please call 02341123333';
var updateString = function(input_text) {
//1. Find consecutive 11 numeric digits
var match = input_text.match(/\d{11}/);
//2. divide it into a string of 3s separated by space
var new_str = '';
for (var i = 1; i < match[0].length + 1; i++) {
new_str = new_str + match[0][i - 1];
if (i > 1 && i % 3 == 0)
new_str = new_str + ' ';
}
//3. Replace old match no. with the new one
console.log(match)
if (match[0] != '')
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
confirm_value.value = "Yes";
input_text = input_text.replace(match[0], new_str)
$('#loutput').val(input_text);
confirm2()
//document.getElementById('loutput').innerHTML = input_text;
} else {
confirm_value.value = "No";
confirm2()
}
$('#loutput').val(input_text);
//document.getElementById('loutput').innerHTML = input_text;
};
updateString(str);
};
function confirm2() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(" send the message now?")) {
confirm_value.value = "Yes";
document.getElementById('button2').click();
//document.getElementById('loutput').innerHTML = input_text;
} else {
confirm_value.value = "No";
}
//document.getElementById('loutput').innerHTML = input_text;
};
</script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<form runat="server" action="formatmessage3.aspx" method="post">
<input type="texarea" id="loutput" name="loutput" value="<%=request.form ("loutput") %>" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>
<asp:button ID="button2" OnClick="sendmsg" Text="send" runat="server" />
</form>
</body>
</html>
The problem here is the fact you are using a .NET button with runat="server" so it is going to change the id of the button to a different value.
<asp:button ID="button2" OnClick="sendmsg" Text="send" runat="server" />
You either have to reference the element by a class
document.getElementsByClassName("myClass")[0].click();
or reference the dynamic name
document.getElementById("<%= button2.ClientID %>").click();
or in .NET4 you can use ClientIDMode="Static"

JavaScript Pass button id to an asp.net hiddenfield

I got a silly question just as the question stated,the failed code shown below:
<script type="text/javascript">
function HISenlarge(id) {
var parent = id;
document.getElementById('HiddenField1').value = parent;
}
</script>
HTML:
<button type="button" id="kkkk" onclick="HISenlarge(this.id)"></button>
<asp:HiddenField ID="HiddenField1" runat="server" value=""/>
VBcode
Protected Sub CommentButton_Click(sender As Object, e As EventArgs) Handles CommentButton.Click
Dim c_id As String
c_id = HiddenField1.Value.ToString
document.getElementById('HiddenField1').value = parent;
This is not a HTML for the HiddenField1.So you should reference it by its ClientID
document.getElementById('<%=HiddenField1.ClientID %>').value= parent;

Unable to bind JSon to list in Angular JS

i am developing an application using angular js in which i have to populate the customer list using data in database for that i write a web method to get the data like
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getname()
{
SqlHelper sql = new SqlHelper();
DataTable dt = sql.ExecuteSelectCommand("select cust_F_name,cust_L_name from customer");
Dictionary<string, object> dict = new Dictionary<string, object>();
object[] arr = new object[dt.Rows.Count];
List<CustName> custName = new List<CustName>();
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
CustName c = new CustName();
c.cust_F_name = dt.Rows[i]["cust_F_name"].ToString();
custName.Add(c);
}
dict.Add("JsonCustomer", custName);
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
//return "Rhsuhikesh";
}
}
public class CustName
{
public string cust_F_name { get; set; }
}
catch that Json data as
var DemoApp = angular.module('DemoApp', []);
DemoApp.factory('SimpleFactory', function ($http) {
return {
getCustomer: function () {
return $http.post('Home.aspx/getname', { name: "" });
}
};
});
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customer) {
$scope.Customer = customer.data;
}, function (error) {
// error handling
});
});
and view it as
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DemoApp">
<head runat="server">
<title></title>
</head>
<body data-ng-controller="SimpleController">
<form id="form1" runat="server">
<div>
Name<input type="text" data-ng-model="Name" />{{ Name }}
<ul>
<li data-ng-repeat="customerName in Customer | filter:Name">{{ customerName }} </li>
</ul>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="Script/Home.js" type="text/javascript"></script>
</body>
</html>
and I am getting o/p as
but i want it as
data in json i have to access in name value pair but i am not understand how to do it please help me to out if it.
thanks in advance.
Since you get your results as JSON string you need to convert it to JavaScript object using angular.fromJson
For example:
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customerData) {
var customersRawObject = angular.fromJson(customerData);
}, function (error) {
// error handling
});})
Then you can do somthing like this:
$scope.customerA=customersRawObject.JsonCustomer[0];

Categories

Resources