What is the point of HttpApplication.CompleteRequest()? - asp.net

I have made a simple web form with some static HTML on the design view, and on the code behind I put on two methods: Page_Load and Page_PreRender as follows:
public partial class SamplePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ClearContent();
Response.ClearHeaders();
Response.StatusCode = (int)HttpStatusCode.NotFound;
Respons.Write("Not Found");
Context.ApplicationInstance.CompleteRequest();
}
protected void Page_PreRender(object sender, EventArgs e) // Why does this event get called? Should not the CompleteReqeust()
{ // cause the page to jump directly to the end of events pipeline?
throw new NotImplementedException();
}
}
Moreover, I have read so many Q&As about Response.End() being "ugly", "dangerous", etc, even from MSDN website. But it puzzles me a lot, why if so the Response.Redirect(string) still uses Response.End() internally?

Overriding IHttpHandler's ProcessRequest(HttpContext) in the Page is enough to do the trick.
public partial class SamplePage : System.Web.UI.Page
{
public override void ProcessRequest(System.Web.HttpContext context)
{
if (conditionTrue)
{
context.Response.StatusCode = 404;
context.ApplicationInstance.CompleteRequest();
}
else
{
base.ProcessRequest(context);
}
}
protected void Page_Load(object sender, EventArgs e) // This is not called also :P
{
}
protected void Page_PreRender(object sender, EventArgs e) // Not called now :)
{
throw new NotImplementedException();
}
}

Related

ASP.Net OnLoad Stop event handling

I have some validation code in my WebForm page. When a user clicks on a button and does a postback.
Page_Load event gets processed then the Button1_Click event gets processed.
I can't figure out a way to stop the Button1_Click event from processing if the validation fails on Page_Load.
Is a trick to do this?
Thanks
4 variations shown below.
public partial class _Default : System.Web.UI.Page
{
private bool MyPageIsValid { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
bool valid = false; /* some routine here */
MyPageIsValid = valid;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (this.MyPageIsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!this.MyPageIsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.Page.IsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (!this.Page.IsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
I think it should be better to check validation conditions exactly in the Button1_Click method like this:
if (!this.IsValid()) { return; }
Also if you still want to check that conditions in Page_Load method just add simple 'bool isValid' flag to your page's class and then check it in Button1_Click:
if (!this.isValid) { return; }

Update controls field when page load

I fill some controls with data from data base, by calling a select method
and I change the values to update it, but when I press update button, it takes the values that called at the page load, and ignore all changes.
how can I avoid this ?
thanks in advance : )
here is a simple code to present my problem
SelectBLL _selectbll;
string _title = string.Empty;
string _details = string.Empty;
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
GetUMedicineDetails();
}
#endregion
#region Get UMedicine Details
private void GetUMedicineDetails()
{
_selectbll = new SelectBLL();
_selectbll._GetUMedicineDetails(Request.QueryString[0].ToString(), ref _title, ref _details);
#region Bind Controls
txtdetails.Text = _details;
txttitle.Text = _title;
#endregion
}
#endregion
#region Update Button
protected void btnupdate_Click(object sender, EventArgs e)
{
_UpdateUMedicine();
}
#endregion
#region UpdateU Medicine
public void _UpdateUMedicine()
{
_updatebll = new UpdateBLL();
_updatebll._UpdateUMedicine(
Convert.ToInt32(Request.QueryString[0]), txtdetails.Text, txttitle.Text);
}
#endregion
Page.IsPostBack Property: Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetUMedicineDetails();
}
}
Also, Refer:
How to: Determine How ASP.NET Web Pages Were Invoked
DataBind only if !Page.IsPostaBack:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostaBack)
GetUMedicineDetails();
}

Why does DataPager need Pre-Render event to work??

Having to use pre render is causing me problems.. It would be great if I did not need it.. The problem is I have the list in a user control and when I goto the next 'page' I databind.. but then the datapager prerenders.. which also does a batabind.. so it runs twice..
If I remove the prerender .. then clicking next 'page' does nothing..
Any idea?
protected void Page_Load(object sender, EventArgs e)
{
GetSearchResults();
}
//protected void dpMembers_PreRender(object sender, EventArgs e)
//{
// GetSearchResults();
//}
public void GetSearchResults()
{
List<Person> listPerson = new List<Person>();
string strServer = "localhost";
string strAppPath = Server.MapPath("/");
PersonBusiness pb = new PersonBusiness(new PersonRepository());
listPerson = pb.GetAllPersons(strServer, strAppPath);
lvPersons.DataSource = listPerson;
lvPersons.DataBind();
}
Modify your Page load to
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
GetSearchResults();
}
}
your prerender seems ok.

Have to press Enter Twice for a function to work C#

I have the following .aspx page. I'm searching for the words that are in the database, everything works fine. I also have a HyperLink which shows a message if the word does not exist in the database.
BUT the only problem is when I search for the word and the word is not in the database it doesn't show the HyperLink from the first time, I have to CLICK ENTER twice for it to work, and CLICK CLEAR twice for it to dissapear.
I know that the problem is that I have the button after the page_load, but I can't find the solution for it. What I've tried is created another function private void load_data() and copy everything from page_load into it. And in the load_page and button2_click just call load_data(); It doesn't work.
Here's the code:
namespace TRI_Portal.ScreenPop.Gloss
{
public partial class Gloss_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (GridView2.Rows.Count == 0)
{
HyperLink1.Visible = true;
}
else
{
HyperLink1.Visible = false;
}
String s = Request.QueryString["language"];
Language1.Text = Server.HtmlEncode(s);
}
}
}
I have tried this as well, but no luck.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetLink();
}
}
private void SetLink()
{
if (GridView2.Rows.Count == 0)
{
HyperLink1.Visible = true;
}
else
{
HyperLink1.Visible = false;
}
String s = Request.QueryString["language"];
Language1.Text = Server.HtmlEncode(s);
}
protected void Button2_Click(object sender, EventArgs e)
{
SetLink();
}
Any suggestions?
Handle GridView.DataBound event
protected void GridView1_DataBound(object sender, EventArgs e)
{
SetLink();
}
And markup:
<asp:GridView OnDataBound="GridView1_DataBound" ....
Remove the code from the Page_Load event.

How to do that fields not initialization?

how to do that every time s_Sort not update SortDirection.Desc
private SortDirection s_Sort = SortDirection.Desc;
protected void Page_Load(object sender, EventArgs e)
{
lblSort.Text = S_Sort.ToString();//every time == SortDirection.Desc - this is bad!
if (!IsPostBack)
{
ShowTree();
Validate();
}
}
Need
public void btnSortUp_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Asc;
}
public void btnSortDown_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Desc;
}
but after SortDirection.Desc is bad
The is a problem of the ASP.NET lifecycle. Every time a postback happens (for example, when btnSortUp or btnSortDown is clicked), a new instance of your page is created, i.e., S_Sort is reinitialized to Desc. If you want to persist the value between postbacks, you can store it in the viewstate, for example, by encapsulating it in a private property:
private SortDirection S_Sort {
get { return (SortDirection)(ViewState["S_Sort"] ?? SortDirection.Desc); }
set { ViewState["S_Sort"] = value; }
}

Resources