Using Programmatic Images in Nivo SLider with asp.net and c# - c#

"Only images or images wrapped in links are allowed in the slider div. Any other HTML will break the slider."
What would be the best way to programatically insert images from a database in c#?
I was using a label inside the div id="slider" tag but then realized the label would create the images within a span tag and therefore break the slider.
lblSlider.Text += "<img src=\"" + URL + "\" alt=\"" + address + "\" title=\"<a href='Featured/" + address" + address + ", " + city + "</a>\" />";

Use markup like this...
<img src='ImageHandler.ashx?ProductID=<%# Eval("ProductID")%>'
alt="<%# Eval("ProductName") %>" title="<%# Eval("ProductName") %>" />
... in conjunction with an image HttpHandler class like this (adapt for your own particular DB schema):
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["productID"] != null)
{
try
{
string ProductID = context.Request.QueryString["ProductID"];
if (Convert.ToInt32(ProductID) > 0)
{
const string CONN
= "Initial Catalog=xxx;Data Source=xxx;Integrated Security=SSPI;";
string selectQuery
= "SELECT Photo FROM dbo.Products WHERE dbo.Products.ProductID="
+ ProductID.ToString();
SqlConnection conn = new SqlConnection(CONN);
SqlCommand cmd = new SqlCommand(selectQuery, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
dr.Close();
conn.Dispose();
// context.Response.End();
// caused an "Abort thread" error
// - this is correct and is a special exception
}
}
catch (Exception ex)
{
ErrorReporting.LogError(ex);
}
}
else
throw new ArgumentException("No ProductID parameter specified");
}
public bool IsReusable
{
get
{
return true; // multiple images otherwise false
}
}
}

Okay, I haven't tried the other solution but I did this and it works:
Here are some global c# variables:
protected int count;
protected string[] arr = new string[20];
Then I assign values to the string array from my database in the Page_Load method.
And then I just write the nivo slider with javascript on my page:
<script type="text/javascript">
document.write("<div id='slider' class='nivoSlider'>");
var count = <%= count %>;
var myArray = <% = new JavaScriptSerializer().Serialize(arr) %>;
for(var i = 0; i < count; i++) {
document.write(myArray[i]);
}
document.write("</div>");
</script>
This solution seems easier to me, but if anyone thinks I should use the other solution over this one, let me know. Oh, and don't forget the namespace System.Web.Script.Serialization

I have same requirement and tried the below code to accomplish the dynamic loading of images basing on category. These image loaded from my database. I am new to ASP.Net please let me know if I did anything wrong or did any blunders :).
in ASP.Net file:
I am using nivo slider append method
<script type="text/javascript">
$(window).load(function() {
$('#slider').append('<img id="ad5" src=<%=__ad1ImageUrl %> />');
$('#slider').append('<img id="ad6" src=<%=__ad2ImageUrl %> />');
$('#slider').append('<img id="ad7" src=<%=__ad3ImageUrl %> />');
$('#slider').append('<img id="ad8" src=<%=__ad4ImageUrl %> />');
$('#slider').nivoSlider();
});
</script>
My table looks like this:
<table style="height: 183px; width: 100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="left">
<div id="wrapper">
<div class="slider-wrapper theme-default">
<div class="ribbon">
</div>
<div id="slider" class="nivoSlider">
<!-- note that no images added here -->
</div>
</div>
</div>
</td>
</tr>
</table>
In the code behind:
Use variable to store image url(s). You can now get the URL(s) from DB and get populated. In my code i have used these variables (can use array also) to capture url path. You can get the paths from any source like Database, Xml or ...
public string __ad1ImageUrl = "";
public string __ad2ImageUrl = "";
public string __ad3ImageUrl = "";
public string __ad4ImageUrl = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
__ad1ImageUrl = "UserControls/Images/mainBanner1.jpg";
__ad2ImageUrl = "UserControls/Images/mainBanner2.jpg";
__ad3ImageUrl = "UserControls/Images/mainBanner3.jpg";
__ad4ImageUrl = "UserControls/Images/mainBanner4.jpg";
}
}

Related

Dynamically generated div InnerHtml rendering very different than when statically coded

I have the following html markup in a form with with and UpdatePanel. This code is rendering/displaying exactly as I want when statically coded. However, when I use a while loop in the c# codebehind to dynamically concatenate the code for all the 'docbox' elements into a string then set that string into InnerHtml for div 'bookshelf_items', it renders/displays very differently. It appears that after the first .docbox div is generated, the subsequent docbox divs are inside it. Another bizarre thing is that everything that should display after 'bookshelf_items' disappears.
Edit
<div class="bookshelf_items" id="bookshelf_items" runat="server">
<div class='docbox'>
<div class='doc' contenteditable='true' id='doc_50'>
<div class='doc_title'>TEST TITLE</div>
<div class='doc_txt'>TEST TEXT</div>
</div>
<div class='doc_date'>TEST DATE</div>
<div class='doc_del' ID='del_50' runat='server' />
<div class='doc_getlyt' ID='getlyt_50' runat='server' />
</div>
</div>
Edit - removed the CSS
Edit - removed the C# codebehind
Try this
private void GetUserDocs(string user_id)
{
using (SqlConnection connection = new SqlConnection(conn))
using (SqlCommand cmd = new SqlCommand("SELECT id, title, alias, dt from dbo.user_works WHERE user_id = #user_id", connection))
{
cmd.Parameters.AddWithValue("user_id", user_id);
connection.Open();
using (var reader = cmd.ExecuteReader())
{
// Check if the reader has any rows at all before starting to read.
if (reader.HasRows)
{
string doclist_html = "<div class=\"bookshelf_items\" id=\"bookshelf_items\" runat=\"server\">";
while (reader.Read())
{
string doc_id = reader["id"].ToString().Trim();
string title = reader["title"].ToString().Trim();
string alias = reader["alias"].ToString().Trim();
string dt = reader["dt"].ToString().Trim();
string date = DateTime.Parse(dt).ToShortDateString();
//build doc html
doclist_html = doclist_html + String.Format(
"<div class='docbox'>" +
"<div class='doc' contenteditable='true' id='doc_x{0}'>" +
"<div class='doc_title'>{1}" +
"</div>" +
"<div class='doc_txt'>{2}" +
"</div>" +
"</div>" +
"<div class='doc_date'>{3}</div>" +
"<div class='doc_del' ID='del_{0}' runat='server' />" +
"<div class='doc_getlyt' ID='getlyt_{0}' runat='server' />" +
"</div>",
doc_id, title, alias, date);
}
doclist_html += "</div>";
bookshelf_items.InnerHtml = doclist_html;
string testhtml = bookshelf_items.InnerHtml;
}
else
{
//username not found
lbl_error.Text = ">>Failed to get documents<<";
}
}
}
}​
I figured out the solution to my own problem and I want to post the answer here in case anyone else runs into the same issue
When setting the InnerHtml into my div, the following code broke the parent/child hierarchy
<div class='doc_del' ID='del_54 runat='server' />
<div class='doc_getlyt' ID='getlyt_54' runat='server' />
The solution was to replace the embedded close characters with specific div close tag as follows:
<div class='doc_del' ID='del_54 runat='server'></div>
<div class='doc_getlyt' ID='getlyt_54' runat='server'></div>
Hopefully this will save someone some time and frustration. I don't know why it works this way. Maybe someone who knows will share. Thanks to those who commented on my issue

Fill elements with data from database

I want do build some pictures albuns that the user can click on it and go to a image gallery with pictures of that album.
Each algum have a thumbnail picture, a title and a link for the pictures.
In my code, I can get all the data from database. But it doesn't appear on the website.
I know I'm doing something wrong. But don't know what...
So, here's my code:
In my model, I have this code:
public List<Entities.Portfolio> GetAlbuns()
{
List<Entities.Portfolio> port = new List<Entities.Portfolio>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("usp_get_all_albuns", connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = null;
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
port.Add(new Entities.Portfolio()
{
Imagem = (byte[])reader.GetValue(0),
Link = reader.GetString(1),
Title = reader.GetString(2)
});
}
}
return port;
}
In my controller, I'll call the method:
PortfolioController pcontroller = new PortfolioController();
protected List<Entities.Portfolio> GetAlbuns()
{
return pcontroller.GetAlbuns();
}
And in my ASP.NET page, I have this:
<div class="freshdesignweb" id="Albuns" runat="server">
<% foreach(var items in GetAlbuns())
{ %>
<!-- start article 1 -->
<article class="border c-two" style="background-image:url('<% items.Imagem.ToArray(); %>"')">
<div style="opacity: 0;" class="fdw-background">
<h4><% Eval(items.Title.ToString()); %></h4>
<p class="fdw-port">
Abrir Álbum <span class="vg-icon">→</span>
</p>
</div>
</article>
<!-- end article 1 -->
<%} %>
I can get all the data well, I tested in debug mode. But it doesn't appear in the page.
I know I'm doing something wrong, can you help me to understand how to fix this?
In my investigation I read about
Thank you.
You are missing the # sign in front of Eval:
"<%# Eval(items.Link.ToString()) %>"

How can I create SQL Query which Takes Parameters from URL in asp.net C#

my link is like
http://localhost/default.aspx?phone=9057897874&order=124556
Here Is my basic Page for passing Parameter In URL from ASP.net
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form method="get" action="default.aspx">
<label>Phone No</label>
<input type="text" name="phone" />
<br />
<label>Order No</label>
<input type="text" name="order" />
<br />
<input type="submit" value="submit" />
<br />
</form>
my c# file where I can store the prameters in Variables
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strQuery;
string phone = Request.QueryString["phone"];
if (phone != null)
{
Response.Write("phone no is ");
Response.Write(phone);
}
else
{
Response.Write("You phone number is not correct");
}
string order_no = Request.QueryString["order"];
if (order_no != null)
{
Response.Write("Order No is ");
Response.Write(order_no);
}
else
{
Response.Write("You Order number is not correct");
}
//How I can Connect to Mysql Server
strQuery = "SELECT order_status where orde01=''" + order_no + "'' and phone01=''" + phone + "''";
Response.Write(strQuery);
}
}
I'm trying to doing something like this but it's only give me whole query as string.
I am new on this topic.
Any help will be appreciate
Thanks
First off, concatenating a sql statement based on input that the user can change, especially when stored as a string is how SQL Injection Vulnerabilities are created. Don't be that guy.
as for tokenalizing your query string, use named parameters. assume this is your query string
?orderid=777&phone=777-777-7777
Response.QueryString["orderid"]
would return '777' and
Response.QueryString["phone"]
woudl return '777-777-7777'
as for your sql injection issue, you have a couple options. one is a parameterized sql statement, see the C# example here: http://rosettacode.org/wiki/Parametrized_SQL_statement
or use a stored procedure with parameters. the least desirable but minimally acceptable option is to regex validate your input parameters strictly, especially killing characters like '=;% -- and a few others.
EDIT: now that I've had some time to work up a sample, check this out. This sample needs to be customized to your database, but its working on my mysql DB with a test table. you will need to install the MySQLConnector pack and add a project reference to 'MySql.Data' before the code will compile correctly.
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
//define some regex patterns for validating our data.
const string PHONEREGEX = #"((\(\d{3}\))|(\d{3}-))\d{3}-\d{4}";
const string ORDERNUMREGEX = #"\d*";
bool isValid = true;
string phone = Request.QueryString["phone"]; //read phone from querystring.
//validate that arg was provided, and matches our regular expression. this means it contains only numbers and single hyphens
if(!string.IsNullOrWhiteSpace(phone) && System.Text.RegularExpressions.Regex.IsMatch(phone, PHONEREGEX)){
Response.Write(HttpUtility.HtmlEncode(string.Format("The phone number is {0}", phone))); //HTML Encode the value before output, to prevent any toxic markup.
} else {
Response.Write("Phone number not provided.");
isValid = false;
}
string orderStr = Request.QueryString["order"]; //read ordernum from querystring
long order = long.MinValue;
//validate that order was provided and matches the regex meaning it is only numbers. then it parses the value into 'long order'.
if(!string.IsNullOrWhiteSpace(orderStr) && System.Text.RegularExpressions.Regex.IsMatch(orderStr, ORDERNUMREGEX) && long.TryParse(orderStr, out order)){
Response.Write(HttpUtility.HtmlEncode(string.Format("The order number is {0}", order))); //use 'long order' instead of orderStr.
} else {
Response.Write("Order number not provided.");
isValid = false;
}
//if all arguments are valid, query the DB.
if (isValid) {
Response.Write(GetOrderStatus( phone, order));
}
}
private static string GetOrderStatus(string phone, long order) {
string status = "";
//create a connection object
string connstring = "SERVER=<YOUR MYSQL SERVER>;DATABASE=<YOUR DATABASE>;UID=<YOUR USER>;PASSWORD=<YOUR PASSWORD>-";//this is a connection string for mysql. customize it to your needs.
MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connstring); //put your connection string in this constructor call
//create a SQL command object
using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand()) { //use a using clause so resources are always released when done.
cmd.Connection = conn;
cmd.CommandText = "SELECT `Order_Status` FROM `<YOUR TABLE>` WHERE `Order` = #order AND `Phone` = #phone"; //this needs a From statement
//add parameters for your command. they fill in the #order and #phone in the sql statement above. customize these to match the data types in your database.
cmd.Parameters.Add("order", MySql.Data.MySqlClient.MySqlDbType.Int64,11).Value = order; //do not use # sign in parameter name
cmd.Parameters.Add("phone", MySql.Data.MySqlClient.MySqlDbType.VarChar, 50).Value = phone;
//execute the command, read the results from the query.
cmd.Connection.Open();
using (MySql.Data.MySqlClient.MySqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
status = reader.GetString("Order_Status");
}
cmd.Connection.Close();
}
}
return status;
}
}
}
You should be using
Request.Form["phone"]
Request.Form["order"]
instead of
Request.QueryString["phone"]
Request.QueryString["order"]
The reason for this is, you are doing a postback and never redirect to a url with those values set as a querystring
However your question title would suggestion your have a url which contains something like
http://yourdomain.com?phone=0123456789&order=17

How i can generate dynamic id for text field and get data from array of model in asp.net 4 mvc3

This is my first post here! :)
I have to return an array of my model from my controller class to the view page. I want to put the data into a text box and generate dynamic id's for each text box to use the data further via JavaScript (that's why I am looking for dynamic id's).
Model
public partial class BhBuyerChart
{
public string Date { get; set; }
public string Quantity { get; set; }
public BhBuyerChart(string n, string d)
{
Date = n;
Quantity = d;
}
}
Controller
public ActionResult test()
{
BhBuyerChart[] model = new BhBuyerChart[7];
DataTable dt = (DataTable)ExecuteDB(ERPTask.AG_GetAllShipmentRecord, CurrentUserId);
List<BhBuyerChart> ItemList = null;
ItemList = new List<BhBuyerChart>();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
model[i] = new BhBuyerChart(dr["Shipmentdate"].ToString(), dr["ShipmentQuantity"].ToString());
i++;
};
return View(model);
}
View
1st Attempt
<div>
<% for (int i=0; i<2; i++) {%>
<%: Html.TextBoxFor(m => m[i].Quantity, new { id = "Quantity"})%> <%--value can assign from model but dnt know how to assing dynamic id --%>
<input type="text" value="<%= i %>" id="text<%=i %>"/> <%--dynamic id can be assinged dnt knw how to assing model value here in textbox --%>
<% } %>
</div>
2nd Attempt
<div>
<% int i = 0; %>
<% foreach (ERP.Domain.Model.BhBuyerChart user in Model) { %>
<% i++; %>
<input type="text"; id="textbox<% i %>" ; value="<% user.Quantity %>" />
<% } %>
</div>
I really appreciate everybody's attention and help and I look forward to your responses!
I think this should do it for you. Effectively what you're going to do is build a new method inside the controller so that you can POST back to the controller with the updated values. Further, you don't want the Quantity fields to have different names because they won't bind - and so each one you build will say Quantity in the name and id attribute when the HTML is generated.
If I've misunderstood your need please comment.
Controller
public ActionResult test()
{
BhBuyerChart[] model = new BhBuyerChart[7];
DataTable dt = (DataTable)ExecuteDB(ERPTask.AG_GetAllShipmentRecord, CurrentUserId);
List<BhBuyerChart> ItemList = null;
ItemList = new List<BhBuyerChart>();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
model[i] = new BhBuyerChart(dr["Shipmentdate"].ToString(), dr["ShipmentQuantity"].ToString());
i++;
};
return View(model);
}
[HttpPost]
public ActionResult test(ICollection<BhBuyerChart> charts)
{
// This allows you to POST to the controller with the modified values
// Note that based on what you're collecting client side the charts
// will ONLY contain the Quantity value, but they will all have one.
// If you need the date you can either show a text box for that or
// even place the date inside a hidden field.
}
View
<form method="post" action="/{controllername}/test">
...
<div>
<% for (int i=0; i<2; i++) {%>
<!-- This line will both bind the value and allow you to POST -->
<!-- this form back to the controller with the new values -->
<!-- NOTE: each control is actually going to be named the same -->
<!-- but when it's posted will post in order to the collection -->
<%: Html.TextBoxFor(m => m[i].Quantity) %>
<!-- You may or may not want this here so that you can get the -->
<!-- value of the date back to the server during a POST -->
<%: Html.HiddenFor(m => m[i].Date) %>
<% } %>
</div>
...
</form>
JavaScript
Now in JavaScript what you can do is use jQuery to simply get a listing of all the elements named Quantity like this and use them from that array.
// with this ([0].Quantity) being the template
// we'll use a simple wildcard selector to find
// all of them that end with Quantity.
var elems = $("[name$=Quantity]")
// now you have a list of the elements that you
// can use to populate the other array with -
// getting the value with a statement like...
var val = elems[0].val();
You need the excellent extension made by Steven Sanderson called BeginCollectionItem. For each row in your Model, each inputs will inherit an unique guid that you can reuse for validation or other stuff.
For more information on how to use the extension step by step, please go see the article on Steven Sanderson's blog : Editing a variable length list, ASP.NET MVC 2-style
The article was made for MVC2 but it work in MVC3 too. It should work in MVC4 but i haven't tested yet.
View
<% foreach (var item in Model) {
<% using(Html.BeginCollectionItem("bhBuyerItem")) { %>
<%= Html.TextBoxFor(m => m.Quantity) %>
<%= Html.TextBoxFor(m => m.Date) %>
<% } %>
<% } %>
The extension method
public static class HtmlPrefixScopeExtensions
{
private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
{
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
string key = idsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null) {
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
queue.Enqueue(previouslyUsedId);
}
return queue;
}
private class HtmlFieldPrefixScope : IDisposable
{
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
this.templateInfo = templateInfo;
previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose()
{
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
}
well after several tries i guess i have able to make this
<%for (int i = 0; i <= 1; i++)%>
<% { %>
<div style="width:100%; float:left">
<%: Html.TextBoxFor(m => m[i].Date, new { id= i+500 })%>
<%: Html.TextBoxFor(m => m[i].Quantity, new { id = i })%>
<%: Html.TextBoxFor(m => m[i].Quantity) %>
</div>
<script type="text/javascript">
var val = [[], []];
for (k = 0; k <= 1; k++) {
val[k][0] = document.getElementById(k+300).value;
val[k][1] = parseInt(document.getElementById(k).value);
}
</script>
this gonna take dynamic data from model array and create dynamic id for each textbox and assign them into variable using dynamic id

Verify Checkbox.Checked from static method

I'm developing a web page for clients to request exemptions from certain requirements. There is a list of 14 CheckBoxes, each with two subsequent Checkboxes. The code to check which of them are checked will be placed in the submit button. This method is in the code behind. Here's the code for that (so far)
[WebMethod]
public void SendForm(string email)
{
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
bool[] desc = new bool[14];
bool[] local = new bool[14];
bool[] other = new bool[14];
for (int i = 1; i <= 14; i++)
{
desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;
/* Do stuff here */
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
I get the error "An object reference iw required for the non-static field, method, or property..."
In the aspx page I have the button and the javascript/ajax that calls the button in the codebehind. Shown here:
<table width='750' align='center'>
<tr>
<td align='left'>
<label>Please Provide your email address:</label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align='left'>
</td>
</tr>
<tr>
<td align='left'>
<fieldset id="Fieldset">
<button onclick="SendForm();">
Send</button>
<button onclick="CancelForm();">
Cancel</button>
</fieldset>
</td>
</tr>
</table>
</form>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
PageMethods.SendForm(email, OnSucceeded, OnFailed);
}
function OnSucceeded() {
$get("Fieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
alert(error.get_message());
}
</script>
As per my knowledge, you can't refer to the controls of a page in the static method until and unless you explicitly pass a reference of the "Page" object to the web method you have written.
Where you have the following code:
bool[] desc = new bool[14];
bool[] local = new bool[14];
bool[] other = new bool[14];
for (int i = 1; i <= 14; i++)
{
desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;
/* Do stuff here */
}
Why don't you have this validation code in a Class in your project.. is there a reason why you are trying to access the PageControls using this code
if (IsValidEmailAddress(email))
{
for (int i = 1; i <= count; i++)
{
CheckBox chkBox = chkDesc1.Checked;
}
}
Change your for loop and start i = 0 and change <= 14 to < 13 C# is 0 based
Place the whole method signature .. you are probably trying to call a non static method inside of your application either add the word static to the method or remove but I would rather see how you have the method created.. also where are you creating the instance of the WebMethod Class object..?

Categories