Response.Redirect executed before the code - asp.net

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");
}
}

Related

how to data bind to dropdownlist when checkbox is checked in asp.net

I have a project that using dropdownlist for choices.When check checkbox1 dropdown automatically bind data from database using table1 and when I check checkbox2 dropdown automatically binding data from database using table2.I do not want to use get data by using any button .How can I do that .Please help me.
here is code by using button:
public void LokasyonDoldur()
{
birimBUS = new BirimBUSV1();
List<BirimVO> birimVO = new List<BirimVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
birimVO = birimBUS.LokasyonlariGetir();
foreach (var item in birimVO)
{
items.Add(new ListItem(item.BirimAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
public void BirimleriDoldur()
{
PoliklinikBUS poliklinikBUS = new PoliklinikBUS();
List<PoliklinikVO> poliklinikVO = new List<PoliklinikVO>();
DrpChcs.Items.Clear();
List<ListItem> items = new List<ListItem>();
poliklinikVO = poliklinikBUS.Poliklinikler();
foreach (var item in poliklinikVO)
{
items.Add(new ListItem(item.PoliklinikAdi, item.ID.ToString()));
}
DrpChcs.Items.AddRange(items.ToArray());
}
protected void BtnLokasyon_Click(object sender, EventArgs e)
{
if (ChckLctn.Checked == true && ChckBrm.Checked==false)
{
LokasyonDoldur();
}
else if (ChckLctn.Checked == false && ChckBrm.Checked == true)
{
BirimleriDoldur();
}
else
{
}
Button1.Visible = true;
BtnLokasyon.Visible = false;
}
protected void DrpChcs_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
KirilimId = Int32.Parse(DrpChcs.SelectedValue);
BPolikilinikID= KirilimId;
}
but I do not want to use this one.
ohh its another language. its hard to read. but what you basicly have to do is check which checkbox is checked in the page load and then load the dropdown based on what is loaded.
something like this. (I have typed it from my head so its not like copy-paste but you get the idea)
page_load
{
if(checkbox1.checked)
{
dropdown.dataitems = items1;
dropdown.databind();
return;
}
if(checkbox2.checked)
{
dropdown.dataitems = items2;
dropdown.databind();
return;
}
}
YOu can call the Button1_click event from the Dropdown list selected index changed event like this
Button1_Click(Button1,new EventArgs());
and in this you can hide that button from the page and in code behind you are calling the same function
OR
You can refactor the code in a seperate function from the button click event and call that function in the selected index changed event.
Please let me knwo if I misunderstood your question
Thanks

ASP.net Page pageload called in postback with IsPost back = false

Hi everyone i have a strange problem which I hope u can help me with,
i have a normal Asp.net page in which i handle some state data in the page load like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["TempD"] = null;
Session["Totals"] = null;
//Handling Sessions here...
}
}
the problem is at a button post back the page_load gets called twice once with IsPostBack
= true which is ok , the second time however IsPostBack = false!!! which cause my code to enter the if condition and reset the state information which is not ok, i use some Ajax Toolkit controls in the page no update panels just some calenders and AutoCompletes.
here is the code for the button causing the post back
protected void TSBtnAddItem_Click(object sender, EventArgs e)
{
if (Session["TempD"] != null)
{
DataLayer.Invoicing.CInvoiceDetail InvoDetails = (DataLayer.Invoicing.CInvoiceDetail)Session["TempD"];
DataLayer.Invoicing.CVarInvoiceDetail var = new DataLayer.Invoicing.CVarInvoiceDetail();
if (LblCurrencyValue.Visible)
{
var.CurencyID = int.Parse(LblCurrencyValue.ToolTip);
}
else
{
var.CurencyID = int.Parse(CboCurrencyValue.SelectedValue);
}
var.ID = 0;
var.InvoiceHeaderID = Convert.ToInt64(InvoiceHeaderID.Value);
var.IsChanges = true;
var.IsFreightItem = false;
var.IsOption = true;
var.ItemAmount = decimal.Parse(txtItemVal.Text);
var.ItemName = CboItemName.SelectedItem.Text;
var.ItemID = int.Parse(CboItemName.SelectedValue);
var.Remarks = "";
if (IsPartLoad.Checked == true)
{
ShipLink.Publics.ApplicationMethods.Item32 itm = LstCalcType.Find(delegate(ShipLink.Publics.ApplicationMethods.Item32 p1) { return Convert.ToInt32(p1.Name.Trim()) == var.ItemID; });
if (itm == null)
{
ADDToCalcList(Convert.ToString(var.ItemID));
if (NumUpDownPortRatio.Enabled == false)
var.ItemAmount = ChangeAmount(var.ItemID, var.ItemAmount);
}
}
InvoDetails.lstCVarInvoiceDetail.Add(var);
Session["TempD"] = InvoDetails;
UGrdInvoiceDetailGrid.DataSource = InvoDetails.lstCVarInvoiceDetail;
UGrdInvoiceDetailGrid.DataBind();
CalcSalesTax();
CalcDiscount();
AddCaseUGrdInvoiceTotalGrid();
}
}
Have a look at this: What is the difference between Page.IsPostBack and Page.IsCallBack?
Integrate if (!IsCallBack) and you should be fine.
I found a solution for this. If you have an global.asax in the project, you need add a new route with "" in a url alias. An example:
private void Generteroutes(RouteCollection routes) {
routes.MapPageRoute("home", "", "~/Default.aspx");
}
load this in Application_Start and problem solved.

ASP:Dropdownlist onselectedindexchanges function does not fire even when I set autopostback to true

I am using a wizard. and in step two the user can add information about a location that will be stored. He can add as many locations as he likes.
In step three I want to enter more information about the specific location.
To select which location to use I have ASP:dropdownlist that I populate when user enters stuff.
I want to change index but it just does not work It never goes into the function when I tried debugging. I am using a label to debug.
When I change the selected item the page reloads and the first item in the dropdown list is always selected even though I selected something else. I do not understand why that happens
here is what I have
ASPX File
Select location to enter data for:
<asp:DropDownList ID="s3_location_list" runat="server" AutoPostBack="true" OnSelectedIndexChanged="stepThree_location_list_SelectedIndexChanged">
</asp:DropDownList>
Current location index:
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
CS files
/*This is where I add data to the drop down list
protected void stepTwo_addLocationData(object Sender, System.EventArgs e)
{
//initialize a temporary string array to get all the data from the form
//Console.Write("AAAAA"+ Context.Items["IsRefreshed"]);
Boolean refreshed = (Boolean)Context.Items["IsRefreshed"];
if (!refreshed)
{
//if user is adding a new entry to the location table
LocationData new_location = new LocationData();
//add stuff to locationData
if (stepTwo_locationTableIndex == -1)
{
//add the new_location element into the location_data array
location_data.Add(new_location);
//redraw the table
DataRow dr = dt.NewRow();
dr["Location"] = new_location.City;
//dr["Name"] = loc;
dt.Rows.Add(dr);
}
else
{
location_data[stepTwo_locationTableIndex] = new_location;
dt.Rows[stepTwo_locationTableIndex]["Location"] = City.Text;
}
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
///CreateTable();
stepFive_setLocationListOptions();
stepThree_setLocationListOptions();
stepTwo_resetForm();
}
/*this is the page load on step 3
protected void stepThree_load()
{
if (!IsPostBack && Session["s_s3_locationDropdownIndex"] == null)
{
stepThree_locationDropdownIndex = s3_location_list.SelectedIndex;
Session["s_s3_locationDropdownIndex"] = stepThree_locationDropdownIndex;
}
else
{
stepThree_locationDropdownIndex = (int) Session["s_s3_locationDropdownIndex"];
}
s3_location_list.SelectedIndex = stepThree_locationDropdownIndex;
Label3.Text = "" + s3_location_list.SelectedIndex;
}
/*this is my where I populate the list
protected void stepThree_setLocationListOptions()
{
s3_location_list.Items.Clear();
int i = 0;
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
/* this is the function thats callled when selected index is changed.
protected void stepThree_location_list_SelectedIndexChanged(object sender, EventArgs e)
{
Label3.Text = "Hello";
}
I think the problem is the order of execution. You should only initialize a DropDownList once, otherwise it will overwrite your SelectedIndex. For example, use the OnInit event:
<asp:DropDownList ID="s3_location_list"
runat="server"
OnInit="s3_location_list_Init"/>
And write the event method like this:
protected void s3_location_list_Init(object sender, EventArgs e)
if (!IsPostBack) {
foreach (LocationData item in location_data)
{
s3_location_list.Items.Add(new ListItem(item.City, "" + i));
}
s3_location_list.DataBind();
}
}

Session Seems to be lost when Button_Click event fired asp.net C#

I am coding an ASP.NET website with C# and Entity Framework.
I stored into a session a Login class I created. The class contains information such as the NetID, the Roles available to the user, and the role the user selects to login as.
The problem I am encountering is that whenever I try to get the information that is stored in the session inside of a Button_Click event, it seems to not get the information. I do not know if this is allowed. However, I also put the Login variable that contains the user information as public variable for any function inside the partial class to access and I still have the same problem accessing the information inside a Button_Click event. When I get the Session information inside the Page_Load event, I am able to get the values that were placed inside that Session.
The following is the code of my program.
public partial class Private_HomePagePortal : System.Web.UI.Page
{
Login SysUser = new Login();
protected void Page_Load(object sender, EventArgs e)
{
string[] Roles;
SysUser.Ticket = Request.QueryString["casticket"];
SysUser.GetNetID();
if (SysUser.Authenticate(SysUser.NetID))
{
SysUser.GetRoles(SysUser.NetID);
Roles = SysUser.Roles;
CasOut.Text = "Welcome <b>" + SysUser.NetID + "</b>! You are now Logged in! " + "Please choose a role you would like to sign in as." + "<br>" + "<br>";
foreach (string item in Roles)
{
if (item == "Admin")
{
Admin.Visible = true;
Admin.CssClass = "btn btn-danger";
AdminBreak.Text = "<br><br>";
}
if (item == "SuperAdmin")
{
SuperAdmin.Visible = true;
SuperAdmin.CssClass = "btn btn-danger";
SuperAdminBreak.Text = "<br><br>";
}
if (item == "Member")
{
Member.Visible = true;
Member.CssClass = "btn btn-danger";
MemberBreak.Text = "<br><br>";
}
if (item == "Convener")
{
Convener.Visible = true;
Convener.CssClass = "btn btn-danger";
ConvenerBreak.Text = "<br><br>";
}
if (item == "ITAdmin")
{
ITAdmin.Visible = true;
ITAdmin.CssClass = "btn btn-danger";
}
}
else
CasOut.Text = "You are not in the IUCommittee System!!!! If you believe this is an error, contact the IT Administrator for assistance.";
Session["Login"] = SysUser;
Login User = (Login)Session["Login"]; //Used to test information is actually in the Session
CasOut.Text = User.NetID;
}
protected void Admin_Click(object sender, EventArgs e)
{
Login User = (Login)Session["Login"];
User.SelectedRole = "Admin";
CasOut.Text = User.NetID + User.SelectedRole;
Session["Login"] = User;
}
}
I would greatly appreciate the help.
Page_Load code will be executed each time when you press the button and in that case value of QueryString value will be erased.
Be ensure that code in page_load gets executed once per page postback (use IsPostBack) or something like:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Login"]==null)
{
string[] Roles;
....
CasOut.Text = User.NetID;
}
}
OR
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string[] Roles;
....
CasOut.Text = User.NetID;
}
}

Passing Value from textboxes in one webform to texboxes in another webform

am trying to get users to enter some details into a textbox in form1 and get the entry validated against the database. if the entry is correct, form2 loads with other texboxes including the one they made entries into. however i dont want them to make any changes to the textboxes they entered values into previously neither should they have to re-enter the values again.
how do i get the values in the textboxes to move from form1 to form2?
the code below shows what ive done with both forms but the second form dosent display the items in the textboxes when the form is loaded.
first form
protected void Button1_Click(object sender, EventArgs e)
{
string strConn;
strConn = "Provider=MIcrosoft.Jet.OLEDB.4.0;data Source=" +
Server.MapPath("App_Data/test.mdb");
OleDbConnection mDB = new OleDbConnection(strConn);
mDB.Open();
prodSnStr = pSnTextBox.Text;
purDate = Convert.ToDateTime(purDateTextBox.Text);
string dateStr = purDateTextBox.Text;
productClass aProduct = new productClass();
if (aProduct.Prods(mDB, prodSnStr, purDate))
{
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
Response.Redirect("Warranty.aspx");
}
else
{
//error message
}
}
form two
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["ProdSn"] != "")
{
pSNoTextBox.Text = Request.QueryString["ProdSn"];
if (Request.QueryString["PurDate"] != "")
{
dateTextBox.Text = Request.QueryString["PurDate"];
}
else
{
//error message to display
}
}
else
{
//error message to display
}
}
eagaerly waiting for your responses..thanks..
In your code you are putting the values on one page into the session:
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
However you are trying to read them out on the 2nd page from the Request collection:
if (Request.QueryString["ProdSn"] != "")
{
pSNoTextBox.Text = Request.QueryString["ProdSn"];
if (Request.QueryString["PurDate"] != "")
{
dateTextBox.Text = Request.QueryString["PurDate"];
}
This makes no sense. If you want to use the session, you must also get the values back out from the session object.
Personally I would look into Cross Page postbacks and Server.Transfer combined with Page.PreviousPage. Just make sure you don't set preserveForm parameter to false if using Server.Transfer.
You aren't passing your values as a query string. If you were your Response.Redirect would look like this:
Response.Redirect("Warranty.aspx?ProdSn=something&PurDate=something");
Instead since you are saving these values in a Session variable try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["ProdSn"] != "")
{
pSNoTextBox.Text = Session["ProdSn"];
if (Session["PurDate"] != "")
{
dateTextBox.Text = Session["PurDate"];
}
else
{
//error message to display
}
}
else
{
//error message to display
}
}
In the button_click of the first form i entered this code
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
Response.Redirect("Warranty.aspx?ProdSn=" + Server.UrlEncode(pSnTextBox.Text) +
"&PurDate=" + Server.UrlEncode(purDateTextBox.Text));
and then in the Page_load event of the second form i did this..
string value = Request["ProdSn"];
string value1 = Request["PurDate"];
pSnTextBox.Text = value;
purDateTextBox.Text = value1;
no hassle sustained....easy and perfectly working....
thank for ya'11 helping....
am very grateful
your asp.net page must post your data to second page.
just set your buttons PostBackUrl attribute.
<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="target.aspx" />
I do not understand while you are making things complex.
When users clicks the button all data will be send to your target page.

Resources