I have an ASP button on my page that is supposed to trigger an event on post back. This used to work but has stopped working on every single page that the search form is on. This particular code has not been updated since I got it all set up and working. The button code looks like:
<asp:Button id="search_button" class="search_button" runat="server" OnClick="search_button_click" />
And the post back event code looks like:
protected void search_button_click(Object sender, EventArgs e)
{
SessionHandler.sqlSearchTerm = searchBox.Text;
if (Int32.Parse(searchCatDdl.SelectedValue.ToString()) > 0)
{
SessionHandler.search_mcat_id = searchCatDdl.SelectedValue.ToString();
}
else
{
SessionHandler.search_mcat_id = "0";
}
Response.Redirect("/search.aspx");
Response.End();
}
I tried replacing the code inside of the event with just Response.Write("Hit");, but it never triggered at all. The page does post back though. There are no extra </form> tags on the page (or any page), leaving just one open form tag and one closing form tag. And like I said, this used to work but now is not.
The only code in the Page_Load method is code that creates drop down options for the search form (which has always worked and still does). There's nothing that would end the output or functionality. I'm trying to get debugging ideas as to how to figure out why this would stop working. I've tried to get the ID of the object used to cause post back but it's coming up blank. Then again, maybe I'm doing it wrong. In the Page_Load method, I did something along the lines of `Request["__(something)"];'. I don't remember exactly what it was, but it was setting that to a string variable which was supposed to have the object ID in it. Anyway, any help would be greatly appreciated.
EDIT
I also want to point out that if I change the OnClick attribute of my button to something that does not exist, it does err out. So it seems as if things are set correctly as I have them (to me, anyway). Also, every other control on the site still works and fires it's post back event.
Here is the panel my control is in:
<asp:Panel cssClass="search_items" id="pnlSearchButton" runat="server" DefaultButton="search_button">
<div class="search_bar">
<table>
<tr>
<td width="200"><h3 class="title">auction items</h3></td>
<td width="230"><asp:TextBox ID="searchBox" runat="server" placeholder="Search" name="search" /></td>
<td width="220">
<div class="select_cont option-set" id="filters">
<asp:DropDownList runat="server" ID="searchCatDdl" cssClass="option-set clearfix" data-filter-group="selectset">
</asp:DropDownList>
</div>
</td>
<td width="70"><asp:Button id="search_button" cssClass="search_button" runat="server" OnClick="search_button_click" /></td>
<td>
<a class="search_icon icon_collapse" id="toggle4"></a>
<div class="search_icon divider"></div>
<div class="search_icon divider"></div>
</td>
</tr>
</table>
</div>
</asp:Panel>
At the top of my page:
<%# Master Language="C#" MasterPageFile="~/master-pages/Site.Master" AutoEventWireup="true" CodeFile="HeaderFooter.master.cs" Inherits="master_pages.HeaderFooter" %>
The entire code behind for this particular page:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CowansRedesign.master_pages
{
public partial class HeaderFooter : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!String.IsNullOrEmpty(Request.QueryString["logout"]))
{
SessionHandler.mailId = "";
SessionHandler.mailName = "";
SessionHandler.mailFirstName = "";
}
if (!String.IsNullOrEmpty(SessionHandler.mailId) && !String.IsNullOrEmpty(SessionHandler.mailFirstName) && Request.ServerVariables["SCRIPT_NAME"].ToString() != "/default.aspx")
{
if (hiName != null) {
hiName.Text = "Hi " + SessionHandler.mailFirstName;
}
}
}
if (!IsPostBack && searchCatDdl != null)
{
Dictionary<string, string> mainCatList = new Dictionary<string, string>();
mainCatList.Add("0", "All Categories");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["wesdb1SQL"].ToString()))
using (SqlCommand strSQL = conn.CreateCommand())
{
strSQL.CommandText = "Select mcat_id, mcat_name " +
"From tblMcat " +
"ORDER BY mcat_name ASC";
try
{
conn.Open();
using (SqlDataReader itemReader = strSQL.ExecuteReader())
{
while (itemReader.Read())
{
mainCatList.Add(itemReader["mcat_id"].ToString(), itemReader["mcat_name"].ToString());
}
itemReader.Close();
}
}
catch (Exception e1)
{
Console.WriteLine(e1.ToString());
//Response.Write(e.ToString());
}
finally
{
conn.Close();
}
}
searchCatDdl.DataSource = mainCatList;
searchCatDdl.DataTextField = "Value";
searchCatDdl.DataValueField = "Key";
searchCatDdl.DataBind();
}
}
protected void overlay_itemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
bool isSaleOnline = Public.isSaleOnline(DataBinder.Eval(e.Item.DataItem, "EventSaleId").ToString());
bool isSaleLotted = Public.isSaleLotted(DataBinder.Eval(e.Item.DataItem, "EventSaleId").ToString());
Image overlayImage = (Image)e.Item.FindControl("overlayImage");
HyperLink auctionLink = (HyperLink)e.Item.FindControl("viewAuction");
HyperLink regLink = (HyperLink)e.Item.FindControl("viewReg");
HyperLink catalogLink = (HyperLink)e.Item.FindControl("viewCatalog");
Label slide_date = (Label)e.Item.FindControl("slide_date");
Label EventName = (Label)e.Item.FindControl("EventName");
EventName.Text = DataBinder.Eval(e.Item.DataItem, "EventName").ToString();
overlayImage.ImageUrl = "http://cowansauctions.com/webimages/events/" + DataBinder.Eval(e.Item.DataItem, "EventMain");
string[] formats = { "MM/dd/yyyy", "MM-dd-yyyy", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd HH:mm:ss" };
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime formattedDate;
//Response.Write(DataBinder.Eval(e.Item.DataItem, "homeDate").ToString());
//Response.End();
DateTime.TryParseExact(DataBinder.Eval(e.Item.DataItem, "homeDate").ToString(), formats, culture, DateTimeStyles.None, out formattedDate);
slide_date.Text = String.Format("{0:MM.dd.yy}", formattedDate);
if (DataBinder.Eval(e.Item.DataItem, "EventSaleId").ToString().Length >= 1)
{
auctionLink.Text = "More about the auction >";
auctionLink.NavigateUrl = "/auctions/details.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventId");
if (isSaleOnline)
{
catalogLink.Text = "View Catalog >";
catalogLink.NavigateUrl = "/auctions/catalog.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventSaleId") + "" + (!String.IsNullOrEmpty(DataBinder.Eval(e.Item.DataItem, "EventStartPage").ToString()) ? "&page=" + DataBinder.Eval(e.Item.DataItem, "EventStartPage") : "");
regLink.Text = "Register to bid online >";
regLink.NavigateUrl = "/auctions/live-bid.aspx";
}
else
{
if (Convert.ToBoolean(DataBinder.Eval(e.Item.DataItem, "EventRegister")))
{
regLink.Text = "Register to bid online >";
regLink.NavigateUrl = "/auctions/live-bid.aspx";
}
if (isSaleLotted)
{
catalogLink.Text = "View Catalog >";
catalogLink.NavigateUrl = "/auctions/catalog.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventSaleId") + "" + (!String.IsNullOrEmpty(DataBinder.Eval(e.Item.DataItem, "EventStartPage").ToString()) ? "&page=" + DataBinder.Eval(e.Item.DataItem, "EventStartPage") : "");
}
}
}
else
{
catalogLink.Text = "View Event Details >";
catalogLink.NavigateUrl = "/event.aspx?id=" + DataBinder.Eval(e.Item.DataItem, "EventId");
auctionLink.Visible = false;
regLink.Visible = false;
}
}
}
protected void search_button_click(Object sender, EventArgs e)
{
SessionHandler.sqlSearchTerm = searchBox.Text;
if (Int32.Parse(searchCatDdl.SelectedValue.ToString()) > 0)
{
SessionHandler.search_mcat_id = searchCatDdl.SelectedValue.ToString();
}
else
{
SessionHandler.search_mcat_id = "0";
}
Response.Redirect("/search.aspx");
Response.End();
}
public static string StripHTML(string htmlString)
{
string pattern = #"<(.|\n)*?>";
return Regex.Replace(htmlString, pattern, string.Empty);
}
}
}
Well, I finally found the issue. I was thinking back and realized the very last change I made was adding Google's Tag Manager code to the website for some SEO tracking. That code turned out to be what was causing this one thing to stop working. I have no clue why. I removed it and everything is working.
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-5XQX2B"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-fdsafdsa');</script>
<!-- End Google Tag Manager -->
Related
I am new to ASP and stuck in a unusual issue. i am using a submit button and written some code to make change in the database and then opening a new page at the end
protected void SaveContentButton_Click(object sender, EventArgs e)
{
if (contentid == 0 )
{
pageCntnt = new content();
}
//value from DropDownList.
pageCntnt.var1 = int.Parse(this.var1.SelectedValue);
pageCntnt.var2 = objCntnt.Text.Trim();
pageCntnt.var3 = objCntnt.Text.Trim();
//Save in the db.
pageCntnt.Save();
//Redirect to test.asp.
Response.Redirect("test.asp");
}
protected void Page_Load(object sender, EventArgs e)
{
contentstring = Request.QueryString["cntntstr"] != null ? Utilities.ToInt32(Request.QueryString["cntntstr"].ToString()) : 0;
if (contentstring > 0)
{
//Get the value from DB
pagecntnt = content.SelectByContentid(contentstring);
}
if (pagecontent != null && !Page.IsPostBack)
{
this.siteid.DataBind();
this.siteid.Items.FindByValue(pagecntnt.var1.ToString()).Selected = true;
TxtBx1.Text = pagecntnt.var2;
TxtBx2.Text = pagecntnt.var3;
}
}`
and my button def is
<div class="floatright">
<asp:Button ID="SaveContent" runat="server" OnClick="SaveContentButton_Click" Text="Submit" />
<input type="button" value="Cancel" onclick="document.location.href='test.asp'" />
</div>
Now my problem is whenever I clicked on submit button page directly goes to test.asp without executing the code above it in the function. I tested by putting ClientScript.RegisterStartupScript(this.GetType(), "On Save pagecontent Location_X", "alert('" + var2.Value + "');", true);
at various places in the SaveContentButton_click function. Whenever I comment the Response.Redirect all above code gets executed and I get all of the alerts and if I uncomment it goes directly to redirect.response, without executing any of the code above it and don't show any of the alerts and also does not go to the save function where I am saving the data in the database.
Please Help.
Thanks in advance.
Try
Response.Redirect("test.asp",false);
If you false it won't abort the thread.
More detail about Response.Redirect is here
If you are trying to Redirect only after successfully making the changes in DB then do something like this:
protected void SaveContentButton_Click(object sender, EventArgs e)
{
bool blnResult = false;
if (contentid == 0 )
{
pageCntnt = new content();
}
//value from DropDownList.
pageCntnt.var1 = int.Parse(this.var1.SelectedValue);
pageCntnt.var2 = objCntnt.Text.Trim();
pageCntnt.var3 = objCntnt.Text.Trim();
//Save in the db.
blnResult = convert.toBoolean(pageCntnt.Save());
//Here i have converted save method into Boolean type so now its going to return True/False
if(blnResult) //Redirect only when blnResult is true
{
//Redirect to test.asp.
Response.Redirect("test.asp");
}
}
I have a pretty straight forward dynamically generated asp page. This is my first time using dynamically generated asp controls. The table renders correctly, however when I click on the "Query" button I cannot get the event to connect to the "OnClick" method. I get a webpage error "'ButtonClick' is undefined". I have stripped and simplified the code down for brevity.
DeviceStatus.aspx
<%# Page Title="Device Status" Language="C#" MasterPageFile="Secure.master"
'AutoEventWireup="true" CodeFile="DeviceStatus.aspx.cs" Inherits="Devices" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id="selectDiv" runat="server"></div>
</asp:Content>
DeviceStatus.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Devices : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
int i, NumberOfDevices = 3;
string Contents;
string[] number = new string[] { "1", "2", "3"};
string[] name = new string[] {"mike", "bob", "cindy"};
string[] location = new string[] { "Austin", "Miami", "Atlanta" };
// Create event binding
PlaceHolder Placeholder1 = new PlaceHolder();
Button button = new Button();
button.Text = "Click";
button.Click += new System.EventHandler(ButtonClick);
Placeholder1.Controls.Add(button);
//Create Form and table header
Contents = "<form runat=\"server\"><table border=\"1\" >";
Contents += "<tr><th>Select</th><th>Number</th><th>Name</th><th>Status</tr>";
// Repeat for each table row
for (i = 0; i < NumberOfDevices; i++) {
// Creat each row
Contents += "<tr><td><asp:Button ID=\"row" + i + "\""
+ "runat=\"server\"OnClick=\"ButtonClick\" >Query</asp:Button></td>"
+ "<td>" + number[i] + "</td><td>" + name[i] + "</td><td>"
+ location[i] + "</td></tr>";
}
// Cleanup
Contents += "</table>";
Contents += "<asp:PlaceHolder ID=\"Placeholder1\" runat=\"server\"></asp:PlaceHolder>";
Contents += "</form>";
Contents += "</asp:Content>";
//Place dynamic asp controls in webpage
selectDiv.InnerHtml = Contents;
}
protected void ButtonClick(object sender, EventArgs e)
{
Response.Redirect("DataRendering.aspx");
}
}
I went with Garrison's suggestion. It took some time to get through the code to figure it out but once completed was the most straight forward solution. Thanks everyone for contributing.
When I click my Remove button it is my intent to remove the Panel, then iterate through the remaining panels and give them a new ID from scratch I.E. if I removed Panel(3) from a list of 6 Panels I would iterate through and give them all new IDs Panels 0-5.
My issue is that I keep running into an error after I delete my panel where I have duplicate ID names. For the life of me I cannot see where I am going wrong so I am reaching out hoping I am just blind or for advice.
I was setting a breakpoint at my btnDelete function and step through it but I am not seeing my logic shortcoming in why I experience an issue with multiple Panels of the same ID.
ASPX:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/MasterPage.master" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" EnableTheming="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<link href="App_Themes/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet"
type="text/css" />
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="Includes/JavaScript/jquery-1.7.1.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.datepicker.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.widget.js" type="text/javascript"></script>
<script src="Includes/JavaScript/jquery.ui.core.js" type="text/javascript"></script>
<%--Script for the Dropdown Datepicker--%>
<script type="text/javascript">
$(function () {
$("input.datepicker").datepicker({ showOn: 'button', buttonImage: 'Includes/Images/calender.gif', buttonImageOnly: false, onSelect: function () { }
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<h1>
Search
<asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="Includes/Images/action_help.gif"
NavigateUrl="~/user_manual.pdf" Target="_blank" ToolTip="Search Help"></asp:HyperLink></h1>
<table border="0" cellpadding="6" cellspacing="0">
<tr>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add Control" onclick="btnAdd_Click" />
<asp:Button ID="btnClear" runat="server" Text="Reset" onclick="btnClear_Click" />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</td>
<td>
<asp:TextBox ID="txtTitle" class="searchPage" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="myPlaceholder" runat="server"></asp:PlaceHolder>
</td>
Code behind:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Search : BasePage
{
List<Users> userroles = new List<Users>();
//Panel that contains all our Dynamically added user controls.
List<Panel> persistControls = new List<Panel>();
public int userid = 0;
public byte IsActive = 1;
public int error = 0;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
// Calls three functions responsible for pulling from the Database and binding the Datagrid.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetClustersFromDB(userid);
BindGrid();
BindState();
}
else
{
// Where I am recreating my controls.
DynamicQueryRecreateLogic();
}
}
protected void DynamicQueryRecreateLogic()
{
if (Session["persistControls"] != null)
{
// Local Value that contains the members of the current persistControls session, not yet pushed to the page.
persistControls = (List<Panel>)Session["persistControls"];
int count = 0;
foreach (Panel panel in persistControls)
{
//AddQuestionTypeDropDownList(count);
panel.ID = "panel" + "(" + count.ToString() + ")";
foreach (Control control in panel.Controls)
{
if (control.GetType() == typeof(DropDownList))
{
control.ID = "list" + "(" + count.ToString() + ")";
DropDownList list = (DropDownList)panel.FindControl(control.ID);
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
}
if (control.GetType() == typeof(TextBox))
{
control.ID = "txtBox" + "(" + count.ToString() + ")";
}
}
// Re-Adding our Remove Button
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = count.ToString();
// Pushing to Placeholder
myPlaceholder.Controls.Add(panel);
myPlaceholder.Controls.Add(btnRemove);
count++;
}
}
}
private DropDownList AddQuestionTypeDropDownList()
{
DropDownList list = new DropDownList();
list.ID = "list" + "(" + persistControls.Count.ToString() + ")";
list.Items.Add(new ListItem("--Select One--", ""));
list.Items.Add(new ListItem("Title", "1"));
list.Items.Add(new ListItem("Contact", "2"));
list.Items.Add(new ListItem("Date Created", "3"));
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
list.AutoPostBack = true;
return list;
}
private TextBox AddFieldTypeTextBox(int count)
{
TextBox box = new TextBox();
box.ID = "txtBox" + "(" + count.ToString() + ")";
return box;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
Panel panelContainer = new Panel();
panelContainer.ID = "panel" + "(" + persistControls.Count.ToString() + ")";
panelContainer.Controls.Add(AddQuestionTypeDropDownList());
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = persistControls.Count.ToString();
persistControls.Add(panelContainer);
myPlaceholder.Controls.Add(panelContainer); // Pushes the Panel to the page.
myPlaceholder.Controls.Add(btnRemove); // Pushes our Button to the page.
Session["persistControls"] = persistControls; // put it in the session
}
catch
{
throw;
}
}
protected static string DecipherCountNumber(string IDHolder)
{
int start = IDHolder.IndexOf("(");
if (start == -1)
{
return IDHolder;
}
else
{
return IDHolder.Substring(start + 1).Replace(")", string.Empty);
}
}
protected void list_SelectedIndexChanged(object sender, EventArgs e)
{
//I need to fix the dynamic Add location. I need to track some type of enumeration or attributes of the panel for recreation.
try
{
DropDownList list = (DropDownList)sender;
string IDHolder = list.ID.ToString();
int count = Convert.ToInt32(DecipherCountNumber(IDHolder));
Panel panelContainer = persistControls.Find(delegate(Panel panel) { return panel.ID == "panel" + "(" + count.ToString() + ")"; });
if (list.SelectedIndex == 1)
{
//panelContainer.Controls.Add(AddFieldTypeTextBox(count));
}
if (list.SelectedIndex == 2)
{
//panelContainer.Controls.Remove(FindControl("txtBox" + "(" + count.ToString() + ")"));
}
if (list.SelectedIndex == 3)
{
//panelContainer.Controls.Remove(FindControl("txtBox" + "(" + count.ToString() + ")"));
}
Session["persistControls"] = persistControls;
}
catch
{
throw;
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
try
{
Session["persistControls"] = null;
Response.Redirect(Request.Url.ToString());
}
catch
{
throw;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
int deleteThisOne = int.Parse(((Button)sender).CommandArgument);
persistControls.Remove(persistControls[deleteThisOne]);
Session["persistControls"] = persistControls;
Response.Redirect(Request.Url.ToString(), false);
}
catch
{
throw;
}
}
I modified my DynamicQueryControls to do the recreation OnInit rather than at PageLoad. Quite a few issues arise from creating this at the PageLoad level.
I am trying to get value from the databse and assign it to the label using the below line:
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString();
but it assigns as label.
if (ds.Tables[0].Rows.Count > 0)
{
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString(); ;
}
UPDATED - Deleted my last info now that you have included the code....
Have you stepped through your code to see if any data is returning?
AKA - is ds.Tables[0].Rows.Count > 0 ?
You are also doing !Page.IsPostBack. This will only call the code and load your labels if it's on the first load.... What about subsequent loads? The labels will return back to whatever they defaulted to in the designer.....
I've put together a test-case in a web app as follows:
ASPX Code-behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var ds = new DataSet();
var table = new DataTable();
table.Columns.Add("Question", typeof(string));
table.Rows.Add(new object[] { "This is the question" });
ds.Tables.Add(table);
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString();
}
}
ASPX Page:
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblQuestion"></asp:Label>
</div>
</form>
This renders out correctly as:
<div>
<span id="lblQuestion">This is the question</span>
</div>
Are you sure you've shown us the code that's actually running?
protected void Page_Load(object sender, EventArgs e)
{
//if (Request.QueryString["QID"] != null)
//{
// Response.Write(Request.QueryString["QID"].ToString());
//}
if (!Page.IsPostBack)
{
int i = Convert.ToInt32(Request.QueryString["QID"]);
// Response.Write(i);
eTutorService ServiceProvider = new eTutorService();
DataSet ds = new DataSet();
ds = ServiceProvider.GetQuestionView(i);
if (ds.Tables[0].Rows.Count > 0)
{
lblQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString(); ;
lblOption1.Text = ds.Tables[0].Rows[0]["Option1"].ToString();
lblOption2.Text = ds.Tables[0].Rows[0]["Option2"].ToString();
lblOption3.Text = ds.Tables[0].Rows[0]["Option3"].ToString();
lblOption4.Text = ds.Tables[0].Rows[0]["Option4"].ToString();
lblCorrectOption.Text = ds.Tables[0].Rows[0]["CorrectAnswer"].ToString();
lblPaper.Text = ds.Tables[0].Rows[0]["subject"].ToString();
lblDifficultyLevel.Text = ds.Tables[0].Rows[0]["LEVEL_NAME"].ToString();
lblquestionOrder.Text = ds.Tables[0].Rows[0]["QuestionOrder"].ToString();
}
}
}
Its just put label rather than putting database value to the label
I have a form with a collection of Html and ASP Server Controls. Im using JSON to preload some drop-down lists.
I want to maintain the states of these drop-down lists on postback. Im quite new to JSON, can anyone help?
If you can use HTML select element instead. Thus, you can get the selected value of select element on the server and register an hidden field to maintain the value. While you are loading the items so you can check the registered hidden field to retrieve the previous selected value.
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script type="text/javascript">
var sv = document.getElementById("SelectedValue");
var v = (sv != null && sv.value != "" ? sv.value : null);
var o = document.getElementById("DropDownList1");
for (var i = 0; i < 10; i++) {
var item = document.createElement("option");
item.innerHTML = "item" + i;
item.setAttribute("value", "item" + i);
if (("item" + i) == v)
item.setAttribute("selected", "selected");
o.appendChild(item);
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
firstly, you should create an HTTPHandler to generate the JSON and get it using getJSON method from jQuery. Lastly, you have to get the selected value on the Load event of the page and maintain the value to a HiddenField for the next time. The following code demonstares it.
public class JsonGenerator : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
JavaScriptSerializer ser = new JavaScriptSerializer();
context.Response.Write(ser.Serialize(new object[]
{
new { Text = "Item1", Value = 1 },
new { Text = "Item2", Value = 2 } ,
new { Text = "Item3", Value = 3 }
}));
}
public bool IsReusable
{
get
{
return false;
}
}
}
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("JsonGenerator.ashx",
null,
function(r) {
var ddl = $("#DropDownList1"), hf = $("#SelectedValue");
$.each(r, function(k, v) {
ddl.append("<option value='" + v.Value + "'>" + v.Text + "</option>");
});
if (hf.length > 0)
ddl.children("[value='" + hf.val() + "']").attr("selected", "selected");
});
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
Don't let the browser do the post, do it yourself with jQuery. On the callback replace a results div with the returned html.
Assuming you've marked your form with class="ajaxform" and your results div with id="results" then something like this (not fully tested)...
// Submit form.ajaxform
// Get the returned html, and get the contents of #results and
// put it into this page into #results
var submit = function() {
$.ajax({
type: "POST",
data: $("form.ajaxform").serialize(),
success: function(data, textStatus) {
$("#results").replaceWith($("#results", $(data)));
}
});
};
$("form.ajaxform input[type=submit]").click(submit);
// I think you'll need this as well to make sure the form doesn't submit via the browser
$("form.ajaxform").submit(function () { return false; });