A pragmatical point of view to ASP.NET's page cycle - c#

I have a form like the following:
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plcHolder" runat="server">
</asp:PlaceHolder>
<asp:Button ID="btnSubmit" Text="submit" runat="server"
onclick="btnSubmit_Click" />
</div>
</form>
And here is my code:
protected string FetchDataFromDatabase()
{
return "some long string";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.plcHolder.Controls.Add(new Label() { Text = FetchDataFromDatabase() } );
}
}
Page_Load() gets a long string from the database.
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.plcHolder.Controls.Add(new Label() { Text = "new text" });
}
My Button adds new text to my page. However, when I click the button, I only see the string "new text" but I was looking for both texts ("some long string new text") instead.
I don't want to call my database at every button click since the text already loaded to the page. How do I achieve this?
I know that this example seems a little weird, it's because I tried to give the minimal working example.

In the load, when you get the value from the database, store it in Session:
Session["textFromDatabase"] = GetTextFromDatabase();
and then leverage that value in both places. So if you were in the click you would say:
... Text = Session["textFromDatabase"] + " new text";
and now you can get the value from the database when it's not a post back, just once like you stated, but leverage it over and over.
And I'm pretty sure, based on what you said, this is the inverse of the condition you want, throw a ! in front of it:
if (Page.IsPostBack)

Related

add multiple innerhtml in asp.net

my x.aspx file :-
<form id ="Content3ret" runat="server">
</form>
<asp:Button ID="Button1" runat="server" OnClick ="Button1_Click"/>
my x.aspx.cs file :-
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
Content3ret.innerhtml = "<table id = '"+x+"'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
}
what I am trying to do is :-
when I click button each and every time there should be new radio button added with other .
like 3 button click I need 3 radio button .
but with this code when I click only one radio button creating .
like 3 click only one radio button with new id.
can anyone help me ?
When you add data on Content3ret.innerhtml and render them on the pages, this data are lost / gone / stay on page and never come back on post back - because this inner html is not post back with the second click on button.
So you have to render them on page, and at the same time saved it somewhere - preferable on viewstate because of asp.net
so the page will be like
<form id="form1" runat="server">
<div runat="server" id="divPlaceOnme"></div>
<asp:Button ID="Button1" runat="server" Text="ok" OnClick ="Button1_Click"/>
</form>
and on code behind we have
const string InnerHtmlKeeper_name = "InnerHtmlKeeper_cnst";
string InnerHtmlKeeper
{
get
{
var RetMe = ViewState[InnerHtmlKeeper_name] as string;
if (string.IsNullOrEmpty(RetMe))
return string.Empty;
else
return RetMe;
}
set
{
ViewState[InnerHtmlKeeper_name] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
// we keep the new with the previous data on this ViewState
InnerHtmlKeeper += "<table id = '" + x + "'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
// we add the final render on the div on page
divPlaceOnme.InnerHtml = InnerHtmlKeeper;
}
Last words.
Your approaches have many issues - and your code not working as it is. The button must be on the form, and you have to render inside some other div.
The point here is to show you have to save some actions on viewstate - beside that for a good solution on your problem you must use some javascript to render the radio without post back.

Get text/value from textbox after value/text changed server side

I have a FormView with data(DataSource,DataBind) that I fill with value='<%# Eval("Name") %>' , but after I'm changing the text in TextBox and press update button I see the same value that before, I cant see new value that I have typed.
What I am missing here?
my html
<asp:FormView ID="MainFormTemplate" runat="server">
<ItemTemplate>
<li class="li_result" runat="server">
<div class="col-3">
<input id="txt_Name" runat="server" value='<%# Eval("Name") %>'>
</div>
</li>
</ItemTemplate>
</asp:FormView>
<asp:Button id="btn_Update" runat="server" OnClick="btn_Update_Click" Text="Update" />
Server side
protected void Page_Load(object sender, EventArgs e)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
public void btn_Update_Click(object sender, EventArgs e)
{
//using System.Web.UI.HtmlControls
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;//i see old value ,not new one that i typed in text box
}
In every postback, you are always getting the old value from your database. The solution is check if the page is being rendered for the first time (!IsPostBack) then set your MainFormTemplate's DataSource else if is being loaded in response to a postback (IsPostBack) get the txt_Name's value like this:
HtmlInputText twt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
else
{
twt = MainFormTemplate.FindControl("txt_Name") as HtmlInputText;
}
}
protected void btn_Update_OnClick(object sender, EventArgs e)
{
string text = twt.Value; // You will get the new value
}
with Page_Load executing every postback, you are always writing value from database (?), and value sent from browser is lost (although still exist in Page.Request.Form member).
In ASP.NET, When a page is submitted, the Page_Load event runs before the button click event. So, the textbox value gets repopulated with its original value before the click event looks at that value.
If this is the situation, then you can wrap the code that assigns the value to the textbox in an if block like this:
if (!IsPostBack)
{
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;
}
Hope this helps you.

Dynamic Div creation asp.net

I am trying to create Div dynamically on the press of button click.
For that i refered this link>> http://forums.asp.net/t/1349244.aspx
and made code on server side(.cs page) as follows>>
public static int i = 0;
protected void Button1_Click(object sender, EventArgs e)
{
i++;
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+i;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
This code was giving me just one div each time when i press the button., I wanted to have addition of divs.
On client side using javascript also i tried>>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="addDiv();" />
</div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
<script type="text/javascript">
function addDiv() {
alert("Control comming in function");
var r = document.createElement('Div');
r.style.height = "20px";
r.style.width = "25px";
r.appendChild("div");
alert("Control going out of function");
}
</script>
Both of these didnt work.
What mistake am i making?
Is there any thing wrong?
Use this
public int Index
{
get
{
if(ViewState["Index"]==null)
{
ViewState["Index"]=0;
}
else
{
ViewState["Index"]=int.Parse(ViewState["Index"].ToString())+1;
}
return int.Parse(ViewState["Index"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "NEWControl"+Index;
newControl.InnerHtml = "This is a dynamically created HTML server control.";
PlaceHolder1.Controls.Add(newControl);
}
It is giving you one div, cause you are adding one div.
Remember that asp.net needs you to create all dynamically added controls on very PostBack after that.
If you want two controls you have to add two to the PlaceHolder.
Just use one parent div with some ID(predefined lets say id="dvDynamic") and runat="server"
and then use it the dvDynamic.innerHTML = "<div> /* dynamic div contents */ </div>"
Its the simplest way, as if you are using html element in ASP.net use dom controls for better generation. Dynamic creation of control will require handled, interface and many things to co-ordinate with that control. As its not predefined by system. you have to create it.
SO choose the DOM element option. that is faster and better :)
I hope this will help :)

Change div things in other page

I used the code below to make a change in div of the page of this code file:
HtmlGenericControl divTest = Page.FindControl("test") as HtmlGenericControl;
divTeste.InnerText = "tested";
But now, I want to change another page. Ex.: default.aspx code behind changes a div inner text in the test.aspx ...
The code above isn't appropriated. I want permanent changes. What code should be?
How can I do it?
You need to understand how ASP.NET works. Introduction to ASP.NET
If you are on Default.aspx and then wont to move to Test.aspx you can use values from Default.aspx in Test.aspx however you can't just change different pages from the page you are on. (Actually it is possible by writing data to a database and then later accessing that data on the page you want to change but for your example I don't believe you are looking for something like that)
The closest to your example I can think of is using a Query string.
Default.aspx Markup
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Default.aspx Code behind
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Test.aspx?DivMSG=Hello");
}
Test.aspx Markup
<div id="MyTestDiv" runat="server">
</div>
Test.aspx Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyTestDiv.InnerText = Request.QueryString["DivMSG"];
}
}
Update:
One way to make it permanent is to write it to a database. A quick example but you need to do the database code
Default.aspx Markup
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Default.aspx Code behind
protected void Button1_Click(object sender, EventArgs e)
{
string messageToWriteToTestDiv = TextBox1.Text;
// Code: to write messageToWriteToTestDiv to the database
}
Test.aspx Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string myMessage = "";
// Code: string myMessage = Get Message from Database to write to div
MyTestDiv.InnerText = myMessage;
}
}
Test.aspx Markup
<div id="MyTestDiv" runat="server">
</div>

Cannot pass a input from text box to a query string and then keep the string in this box

I have a simple ASP.net page:
<form id="form1" runat="server">
<p><asp:TextBox id="input_box" runat="server"></asp:TextBox>
<asp:Button Text="OK" runat="server" OnClick="run" /></p>
</form>
I want to send input from input_box to a query string, and then keep this input in the input_box when the page reloads.
That's the code behind page:
protected void Page_Load(object sender, EventArgs e)
{
input_box.Text = Request.QueryString["input"];
}
protected void run(object sender, EventArgs e)
{
string url = string.Format("?input={0}", input_box.Text);
Response.Redirect(Request.Url.AbsolutePath + url);
}
Problem is that when query string is not empty, string from input_box cannot be passed to query string. How to correct it?
If i understand this correctlly
I think the the post back might be clearing your textbox before sending to the query string.
try adding this to the page load
if (IsPostBack)
return;
This will stop the inputbox being cleared or reset back to the original query string
Hope this help

Categories

Resources