target aspx page is not displayed when crossposting - c#

I am new to ASP.NET.
I am experimenting with webforms. I have 2 pages: NewOrder.aspx which captures the user's order and then crossposts to SaveOrder.aspx where I want to save the order and display some information back to the user.
<telerik:RadButton ID="BtnSubmirOrder" runat="server" ButtonType="StandardButton" AutoPostBack="true"
Text="Place order" PostBackUrl="SaveOrder.aspx">
</telerik:RadButton>
When SaveOrder.aspx is loaded, the code below sets its control values and saves the order. however the browser stays at NewOrder.aspx.
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage==null || !PreviousPage.IsCrossPagePostBack)
Response.Redirect("~/Default.aspx");
var referencingPage = PreviousPage as NewOrder;
int id = Int32.Parse(referencingPage.SelectedPublicationId);
DateTime neededBy = referencingPage.SelectedOrderDate;
LblSummaryIsbn.Text = referencingPage.SelectedIsbn;
LblSummaryNbrCopies.Text = referencingPage.NbrOfOrderedCopies;
DateTime orderDate = DateTime.Now;
LblSummaryOrderDate.Text = orderDate.ToShortDateString();
LblSummaryTitle.Text = referencingPage.SelectedPublicationTitle;
int quantity = Int32.Parse(referencingPage.NbrOfOrderedCopies);
StockContainer _context = new StockContainer();
Order newOrder = Order.CreateOrder(orderDate, quantity, neededBy, id);
_context.Orders.AddObject(newOrder);
_context.SaveChanges();
}
I can see from the javascript that the form's action is set to SaveOrder.aspx when the button is clicked so why is the browser not displaying it?

I think the reason your browser is staying on NewOrder.aspx is that you don't have a button click event associated with your button. Without seeing the rest of your code, I'm not sure why the form's action appears different.
You could do something like the following to introduce a button click event. The redirect logic could go in there.
Markup:
<telerik:RadButton ID="btnSubmit" runat="server" Text="Place Order"
OnClick="btnSubmit_Click" />
Code:
public class NameOfPage
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
// You could do validation here and display an error message if something is not right.
// For simplicity I am assuming the data comes from a set of textboxes.
if (!PageIsValid())
{
return;
}
StockContainer _context = new StockContainer();
Order newOrder = Order.CreateOrder(txtOrderDate.Text, txtQuantity.Text, txtNeededBy.Text, id);
_context.Orders.AddObject(newOrder);
_context.SaveChanges();
// Add your redirect logic here.
}
private bool PageIsValid()
{
if (string.IsNullOrEmpty(txtOrderDate.Text))
{
return false;
}
if (string.IsNullOrEmpty(txtQuantity.Text))
{
return false;
}
// and so on for the other fields that are required.
return true;
}
}

Related

Hiding a linkbutton on the master page

I'm trying to show 2 link buttons in the master page, but these buttons should be Enable/Disable according to the content page. I already retrieve the information from the content page, and it works well, the only thing is that I can't turn enable the buttons once I have disabled them. I have tried several ways, but every attempt seems to do the same. Here is my code.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
ASPxListBox listBoxSA = new ASPxListBox();
listBoxSA = (ASPxListBox)ContentPanelHidden.FindControl("ASPxListBox2");
if (listBoxSA != null)
{
if (listBoxSA.Items.Count > 0)
{
EnableButtons(true);
}
else
{
EnableButtons(false);
}
}
}
else
{
EnableButtons(false);
}
}
public void EnableButtons(Boolean enable)
{
btnNext.Enabled = enable;
btnPrint.Enabled = enable;
}
PS. The boolean is changing its value, but the button is always disabled
I would enclose these buttons in an update panel and tell the update panel to update itself after setting the Enabled property. That should update the buttons with only a partial page update.
HTML
<asp:UpdatePanel ID="MyUpdatePanel" runat="server" UpdateMode="Conditional" ClientIDMode="Static">
<ContentTemplate>
... buttons here ...
</ContentTemplate>
</asp:UpdatePanel>
CODE BEHIND
public void EnableButtons(Boolean enable)
{
btnNext.Enabled = enable;
btnPrint.Enabled = enable;
MyUpdatePanel.Update();
}
because you are using is post back property, once it disabled you should do a post back from your current page and also listBoxSA should not be null.

I'm not able to store the value from the drop down

This is my code, when I run the code in the browser I'm not able to store value to the database I get from the drop down
I tried so many times but failed. Can anyone suggest a fix?
public partial class UserBranchAdminProfile : System.Web.UI.Page
{
public BLLCreateUser blbranchAdmin = new BLLCreateUser();
public Branch branchdetails = new Branch();
public BranchAdminDetails branchProfileDetails = new BranchAdminDetails();
}
protected void Page_Load(object sender, EventArgs e)
{
// if (!IsPostBack)
{
locationSelectDrop.DataSource = blbranchAdmin.getAllBranches();
locationSelectDrop.DataTextField = "BranchLocation";
locationSelectDrop.DataValueField = "BranchId";
locationSelectDrop.DataBind();
}
}
protected void submitProfileButton_Click(object sender, EventArgs e)
{
branchProfileDetails.userId = userIdText.Text;
branchProfileDetails.branchLocation=locationSelectDrop.SelectedValue.ToString();
branchProfileDetails.address = addressTextBox.Text;
branchProfileDetails.phoneNo = phoneNoText.Text;
branchProfileDetails.emailId = emailText.Text;
BLLCreateUser bc = new BLLCreateUser();
bool result = bc.insertBranchAdminProfileDetails(branchProfileDetails);
if (result == true)
{
branchAdminProfileLabel.Visible = true;
}
}
This is my html markup:
<td class="style1">
<asp:Label ID="locationSelect" runat="server" Text="Enter Location"/>
</td>
<td class="style2">
<asp:DropDownList ID="locationSelectDrop" runat="server" style="marginleft:0px"
Width="178px"></asp:DropDownList>
</td>
EDIT:
Are you actually even reading the value of locationSelectDrop in your BranchAdminDetails data object? :)
Every time when you click submit button, The Page_Load will call, and in your code for every post back load event filling your drop down again and setting selected value as 0th position. so un-comment the check of IsPostback in Page_Load event and try to debug again.

Modal popup extender losing ID

Edit:
Added onload method:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
I'm using a modal pop up extender to warn my customers that the item amount of a specific item is over a certain amount.
I have two buttons within this extender that allows a user to confirm they want an email sending to them when new stock arrives or not.
The trigger for the 'yes' button works perfectly but when i send the row ID to the constructor of my class used to store the email details it is always set to 0, even though the variable is global.
Here is my code to explain the issue further:
Button within my modal to add items to the cart:
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
TextBox t = (TextBox)row.FindControl("txtQuan");
*********Gain the item row ID (this is what needs to be passed*******
object ID = GridView1.DataKeys[row.RowIndex].Value;
*********This ID should be passed but is setting to 0************
rowID = Convert.ToInt32(ID);
string qty = t.Text;
int stockToAdd = Convert.ToInt32(qty);
DBHandler add = new DBHandler(rowID);
int qtyCheck = add.getStockQty();
if (stockToAdd > qtyCheck)
{
Button2_ModalPopupExtender.Show();
}
else{
SqlConnection con;
con = add.openDB();
con.Open();
DBHandler idCheck = new DBHandler(rowID);
int rows = idCheck.checkCartRows();
if (rows > 0)
{
int qtyNow = idCheck.getCartQty();
int updateStock = qtyNow + stockToAdd;
idCheck.updateQty(rowID, updateStock);
updatePanel();
}
else
{
idCheck.insertCart(qty);
updatePanel();
}
add.close();
}
}
The following code shows my confirm onclick button method. Note the ID 'rowID' that was stored in the above method when the add to cart button was clicked. This rowID is is setting to 0 instead of holding the rowID value.
protected void btnOK_Click(object sender, EventArgs e)
{
***** rowID is setting to 0*******
DBoutOfStockEmail insertNewEmailDetail = new DBoutOfStockEmail(IDMaster, rowID);
DBMembershipHandler getEmail = new DBMembershipHandler(IDMaster);
string emailToSend = getEmail.emailOfMember();
insertNewEmailDetail.insertDetails(emailToSend);
}
To summaries this question: Why is the rowID variable setting to '0' when i click the yes button with the modal pop up extender?
Based on my initial Comment I am going to post this as an answer
This can be from several things.. are you checking or doing IsPostBack checks, are you holding the Value(s) in a Session Variable..? ViewState is it enabled or disabled..? can you show what your Page_Load Event Looks like

Show dropdown selected value in the grid on the same page

I have a drop down which has the list of delegates. When the user selects a delegate then I populate the available meet-timings in the second dropdown using the selectedindexchange event of the 1st dropdown
Aspx page
<asp:DropDownList ID="delegate_ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddldelegates_SelectedIndexChanged" Width="200px"></asp:DropDownList>
<asp:DropDownList ID="delegatetime_ddl" runat="server" Width="90px"></asp:DropDownList>
<asp:Button ID="adddelegate" runat="server" Text="Add" onclick="adddelegate_Click"/>
.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds1 = getdata.getdelegatelist();
delegate_ddl.DataSource = ds1.Tables[0];
delegate_ddl.DataTextField = "DELEGATE_NAME";
delegate_ddl.DataValueField = "DELEGATE_ID";
delegate_ddl.DataBind();
delegate_ddl.Items.Insert(0, "--Select--");
}
}
protected void ddldelegates_SelectedIndexChanged(object sender, EventArgs e)
{
string delselection = delegate_ddl.SelectedValue.ToString();
DataSet ds2 = getdata.getdelegatetimelist(delselection);
if (ds2.Tables[0].Rows.Count > 0)
{
delegatetime_ddl.DataSource = ds2.Tables[0];
delegatetime_ddl.DataTextField = "TIMESLOT";
delegatetime_ddl.DataValueField = "TIMEID";
delegatetime_ddl.DataBind();
}
else
{
time_lbl.Text = "No slots Open";
}
}
protected void adddelegate_Click(object sender, EventArgs e)
{
string delegateselected = delegate_ddl.SelectedValue.ToString();
string timeslotselected = delegatetime_ddl.SelectedValue.ToString();
getdata.delegatemeetinsert(personidd, delegateselected, timeslotselected);
}
Now the data gets inserted – but my question here is
As soon as the user click add button I would like to display the delegate selected and the time slot selected in a some sort of a grid view or dynamic table below with a delete option.
Can someone please provide a code sample in C# to achieve the above
Instead of using Gridview for displaying data use some basic control like Labels,it will reduce lot's of unncessary code. use Asp.net 'Panel' control and encapsulate all label and button(for delete purpose) into Panel then hide/show according to need. here is the outline of code that might help you,
if(!page.IsPostBack) // This goes into Page_Load
{
Panel1.Visible=false;
}
protected void adddelegate_Click(object sender, EventArgs e) // add this additional code
{
Panel.Visible=True;
GetDelegate()// This method retrieve the delegate you inserted..
Lable1.Text= "Set here Delegate name you just Retrieved"
Label2.Text="Delegate time you retrived"
}
protected void BtnRemovedelegate_Click(object sender, EventArgs e)
{
string Personidd= retrieve person id
string delegateName= Lable1.text;
String timeslot=Label2.Text
SomeDeleteMethod(personidd, delegateName, timeslot);
Panel1.Visible=false;
}
Hope you get the idea..

Dropdownlist SelectedIndexChanged firing on every postback

I am dynamically adding a custom user control to an update panel. My user control contains two dropdownlists and a textbox. When a control outside of the update panel triggers a postsback, I am re-adding the user control to the update panel.
The problem is...on postback when I re-add the user controls, it's firing the "SelectedIndexChanged" event of the dropdownlists inside the user control. Even if the selectedindex did not change since the last postback.
Any ideas?
I can post the code if necessary, but there's quite a bit in this particular scenario.
Thanks in advance!
EDIT...CODE ADDED BELOW
*.ASCX
<asp:DropDownList ID="ddlColumns" OnSelectedIndexChanged="ddlColumns_SelectedChanged" AppendDataBoundItems="true" AutoPostBack="true" runat="server">
*.ASCX.CS
List<dataColumnSpecs> dataColumns = new List<dataColumnSpecs>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillDDLColumns();
}
}
public void fillDataColumnsList()
{
dataColumns.Clear();
//COMMON GETDATATABLE RETURNS A DATA TABLE POPULATED WITH THE RESULTS FROM THE STORED PROC COMMAND
DataTable dt = common.getDataTable(storedProcs.SELECT_COLUMNS, new List<SqlParameter>());
foreach (DataRow dr in dt.Rows)
{
dataColumns.Add(new dataColumnSpecs(dr["columnName"].ToString(), dr["friendlyName"].ToString(), dr["dataType"].ToString(), (int)dr["dataSize"]));
}
}
public void fillDDLColumns()
{
fillDataColumnsList();
ddlColumns.Items.Clear();
foreach (dataColumnSpecs dcs in dataColumns)
{
ListItem li = new ListItem();
li.Text = dcs.friendlyName;
li.Value = dcs.columnName;
ddlColumns.Items.Add(li);
}
ddlColumns.Items.Insert(0, new ListItem(" -SELECT A COLUMN- ", ""));
ddlColumns.DataBind();
}
protected void ddlColumns_SelectedChanged(object sender, EventArgs e)
{
//THIS CODE IS BEING FIRED WHEN A BUTTON ON THE PARENT *.ASPX IS CLICKED
}
*.ASPX
<asp:UpdatePanel ID="upControls" runat="server">
<ContentTemplate>
<asp:Button ID="btnAddControl" runat="server" Text="+" OnClick="btnAddControl_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" ValidationGroup="vgGo" />
<asp:GridView...
*.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
uc_Counter = 0;
addControl();
gridview_DataBind();
}
else
{
reloadControls();
}
}
protected void btnGo_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//THIS BUTTON CLICK IS WHAT'S TRIGGERING THE
//SELECTEDINDEXCHANGED EVENT TO FIRE ON MY *.ASCX
gridview_DataBind();
}
}
private void reloadControls()
{
int count = this.uc_Counter;
for (int i = 0; i < count; i++)
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + i;
upControls.ContentTemplateContainer.Controls.AddAt(i, myUserControl);
((customUserControl)myUserControl).fillDDLColumns();
}
}
private void addControl()
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + uc_Counter.ToString();
upControls.ContentTemplateContainer.Controls.AddAt(upControls.ContentTemplateContainer.Controls.IndexOf(btnAddControl), myUserControl);
//((customUserControl)myUserControl).fillDDLColumns();
this.uc_Counter++;
}
protected int uc_Counter
{
get { return (int)ViewState["uc_Counter"]; }
set { ViewState["uc_Counter"] = value; }
}
Even though this is already answered I want to put an answer here since I've recently tangled with this problem and I couldn't find an answer anywhere that helped me but I did find a solution after a lot of digging into the code.
For me, the reason why this was happening was due to someone overwriting PageStatePersister to change how the viewstate hidden field is rendered. Why do that? I found my answer here.
One of the greatest problems when trying to optimize an ASP.NET page to be more search engine friendly is the view state hidden field. Most search engines give more score to the content of the firsts[sic] thousands of bytes of the document so if your first 2 KB are view state junk your pages are penalized. So the goal here is to move the view state data as down as possible.
What the code I encountered did was blank out the __VIEWSTATE hidden fields and create a view_state hidden field towards the bottom of the page. The problem with this is that it totally mucked up the viewstate and I was getting dropdownlists reported as being changed when they weren't, as well as having all dropdownlists going through the same handler on submit. It was a mess. My solution was to turn off this custom persister on this page only so I wouldn't have to compensate for all this weirdness.
protected override PageStatePersister PageStatePersister
{
get
{
if (LoginRedirectUrl == "/the_page_in_question.aspx")
{
return new HiddenFieldPageStatePersister(Page);
}
return new CustomPageStatePersister(this);
}
}
This allowed me to have my proper viewstate for the page I needed it on but kept the SEO code for the rest of the site. Hope this helps someone.
I found my answer in this post .net DropDownList gets cleared after postback
I changed my counter that I was storing in the viewstate to a session variable.
Then I moved my reloadControls() function from the Page_Load of the *.ASPX to the Page_Init.
The key was dynamically adding my user control in the Page_Init so it would be a member of the page before the Viewstate was applied to controls on the page.

Categories

Resources