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.
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 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
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;
}
}
I have a page with several different usercontrols.
All of them run the following code:
var member = System.Web.Security.Membership.GetUser();
MemberProfile mp = MemberProfile.GetUserProfile(member.UserName);
string affilID = mp.GetPropertyValue("aID").ToString();
I would like to get this value once and save it for use with all the controls.
I'm not sure where in the life cycle I need to do this to insure it is accessible to all the controls when they are being rendered.
Any suggestions?
Thank you!
Why not do it in the Page_Load event with Session? Maybe something like this (C#):
MembershipUser member;
MemberProfile mp;
string affilID;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["member"] != null)
{
member = (MembershipUser)Session["member"];
}
else
{
member = System.Web.Security.Membership.GetUser();
}
if (Session["mp"] != null)
{
mp = (MemberProfile)Session["mp"];
}
else
{
mp = MemberProfile.GetUserProfile(member.UserName);
}
if (Session["affilID"] != null)
{
affilID = (string)Session["affilID"];
}
else
{
affilID = mp.GetPropertyValue("aID").ToString();
}
}
If it's all on the same page, as long as it's outside of a subroutine you should be able to use it within any subroutine. Or am I missing something?
I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:
public partial class Caravan_For_Sale : System.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = null;
switch (check)
{
case "0-1500":
break;
case "1500-2000":
dt = caravans.GetFilterbyPrice1();
break;
case "2000+":
break;
default:
dt = caravans.GetAllCaravans();
break;
}
// DataTable dt = caravans.GetAllCaravans();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
DataList1.RepeatColumns = 3; // 4 items per line
DataList1.RepeatDirection = RepeatDirection.Horizontal;
DataList1.DataSource = pds;
DataList1.DataBind();
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
doPaging();
}
protected void lnkPrice2_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
check = _sender.CommandArgument;
// items["test"] = test;
DataTable dt = caravans.GetFilterbyPrice2();
if (dt.Rows.Count < 3)
{
lnkbtnNext.Enabled = false;
lnkbtnPrevious.Enabled = false;
}
CurrentPage = 0;
BindGrid();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated
As far as I know, you have two options:
1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.
2) Put it in the ViewState just like this:
ViewState["check"] = check;
And load it after with this:
string check = Convert.ToString(ViewState["check"]);
Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.
For example
ViewState("Variable") = "Your string"
Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.