c# how to retrieve post data - c#

If I have a textbox txtInfo in a form that I submit via post, if I post back to the page I can read the value entered in the textbox using txtInfo.Text. What if I am posting to a different page? Do I have to parse Request.Form for the control name mutilations (which is what I am doing now) or can I get it from that mess .net passes around as state?
Thanks
Thank you for the answers so far... Sorry I should have been a little more clear. This control is a runat="server" control. This is what I am relegated to now - not very pretty.
foreach (String key in page.Request.Form.AllKeys)
{
String[] controlName = key.Split('$');//remove that horrrible .net naming - thanks Bill.
keyName = controlName[controlName.Length - 1];//get the last value so we always have the name
keyValue = page.Request.Form[key];
if (keyValue != "")
{
switch (keyName)...

You should look into Cross Page Postbacks.
As noted on this page you can easily get access to txtInfo using the following:
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("txtInfo");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}

What's wrong with...
string txtInfo = Request.Form["txtInfo"];
if(txtInfo == null) txtInfo = "";

A simple solution would be use a simple <input type="text"> instead of an <asp:TextBox>. Give it a name attribute and then access it via Request.Form.
.aspx file:
<input type="text" name="foo" />
Posted-to code-behind (same page, different page, doesn't matter):
var text = Request.Form["foo"];

Related

Invoke button click programmatically

I want to programmatically click button on a webpage with source like this
<input alt="BusiBtn" class="aButtn" type="submit" value="Search" tabindex="16">
When I do
WebBrowser b = new WebBrowser();
b.Navigate(URL);
while (b.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
b.Document.GetElementByID("BusiBtn").InvokeMember("click");
I get "Object reference not set to an instance of object error".
Can somebody help.
Thanks
Rashmi
What you can do in this case simply find all the HtmlElements having input tag. If you need to invoke all the input tags in general, then just invoke click on them. And if you need only the above input element, then filter all the input tags to search for the specific tag with the attribute values like above. Please have a look at the following code:
HtmlElementCollection elems = b.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
string altStr = elem.GetAttribute("alt");
string classStr = elem.GetAttribute("class");
string typeStr = elem.GetAttribute("type");
string valueStr = elem.GetAttribute("value");
string tabindexStr = elem.GetAttribute("tabindex");
if((altStr == "BusiBtn") && (classStr == "aButtn") && (typeStr == "submit") && (valueStr == "Search") && (tabindexStr == "16"))
{
elem.InvokeMember("click");
break;
}
}
You're using the wrong field.
alt is for alternative text.
You have not actually given that button an id of BusiBtn.
Try:
<input id="BusiBtn" class="aButtn" type="submit" value="Search" tabindex="16">
The clue is in the GetElementByID call. It's not called GetElementByAlt for a reason ;)
add 'name' property to input tag and then use GetElementsByName property
You should use the GetElementsByTagName method instead of GetElementById to get all Input-Elements on the page and then cycle through using GetAttribute. An example can be found here http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.getelementsbytagname(v=vs.110).aspx.

How to assign dynamic placeholder to Textbox?

I know this question is asked before for assigning text to textbox, but they didn't have answers or the given answers didn't work for me. I have a static function for translations and I'm trying to use that to assign a placeholder to a Textbox. How can I do it in aspx page?
My code is:
<asp:TextBox ID="search" runat="server"
placeholder='<%# islem.DilGetir(7) %>'>
</asp:TextBox>
This one returns this sourcecode:
<input name="ctl00$search" type="text" id="ctl00_search">
You should set this attribute from the page code behind:
search.Attributes["placeholder"] = islem.DilGetir(7)
you can use ajax controll toolkit text box watermark I find it to be mnost usefull in aspx apps
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
<asp:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" TargetControlID ="search" WatermarkText="textthe my name" WatermarkCssClass="watermarked">
</asp:TextBoxWatermarkExtender>
on the back end
TextBoxWatermarkExtender1.WatermarkTex=islem.DilGetir(7);
I experienced the same problem. The exact solution: Take all placeholder's text to hiddenfield component(separated with , ) and with JS, take the inside array hiddenfield text and assign to input text's placeholder attr with jQuery or JS.
this code for multiselectbox choosen js and normal selectbox.
public void SelectFill(DataTable dtResult, HtmlSelect htmlSelect, string placeHolder, string textColumn, string valueColumn, string value)
{
htmlSelect.DataSource = dtResult;
htmlSelect.DataTextField = textColumn;
htmlSelect.DataValueField = valueColumn;
htmlSelect.DataBind();
bool isMultiple = false;
foreach (var item in htmlSelect.Attributes.Keys)
{
if (item.ToString() == "multiple")
{
isMultiple = true;
}
}
if (isMultiple)
{
htmlSelect.Attributes["data-placeholder"] = placeHolder;
}
else
{
ListItem placeHolderItem = new ListItem(placeHolder, "-1");//create placeholder option for non multible selectbox
placeHolderItem.Attributes.Add("disabled", "disabled");
htmlSelect.Items.Insert(0, placeHolderItem);
htmlSelect.Items[0].Selected = true;
}
}

How to get HiddenField control in Masterpage and set it's value?

I have a MasterPage that contains a hidden field control. I want to get the current value of the hidden field and set the value of it from pages that use the MasterPage.
I have the following code so far: (in one of the pages)
//Get the textbox and set it's value
TextBox txt1 = new TextBox();
txt1 = (TextBox)this.Master.FindControl("txtHiddenField");
txt1 .Text = "true";
The above code does not seem to work. What code would I need to get the hidden field control and set it's value? (and get it's value)
I would recommend to provide a public property/method in your MasterPage, that you can use to set/get the HiddenField's value.
in your Master(assuming it's type is called SiteMaster):
public String HiddenValue {
get{return txtHiddenField.Value;}
set{txtHiddenField.Value = value;}
}
In your page:
SiteMaster master = (SiteMaster)Page.Master;
master.HiddenValue = "true";
This approach is straight-forward, less prone to errors and easily readable. You could even change the control in your master without needing to change the pages(f.e. if you want to replace the hidden-field with a TextBox).
Assuming that your "true" value indicates that you actually want to store a boolean, i would recommend to use a bool as data-type for the property and a self-explanatory name. Then you can store it in the hiddenfield but the client(the page) does not need to know.
HiddenField sets its text as VALUE, while TextBox has a TEXT property. Of course casting one to the other and setting text property won't help.
Do this instead:
HiddenField hiddenField = (HiddenField)Master.FindControl("txtHiddenField");
hiddenField.Value = "true";
Assuming you have added hidden field control like this ->>
<input type="hidden" ID="hiddenFieldID" runat="server" />
you can access it like -->>
HtmlInputHidden hiddenfield = (HtmlInputHidden)this.Master.FindControl(
May be you are missing ContentPlaceHolder
Try something like this
ContentPlaceHolder mpContentPlaceHolder;
TextBox mpTextBox;
mpContentPlaceHolder =
(ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if(mpContentPlaceHolder != null)
{
mpTextBox =
(TextBox) mpContentPlaceHolder.FindControl("TextBox1");
if(mpTextBox != null)
{
mpTextBox.Text = "TextBox found!";
}
}
Read more about Reference ASP.NET Master Page Content

GetElementById without id and name HOW?

I need to click the button "Add" in the post new wordpress form, this button is to add tags to the post , the trouble is that button don't have the value and id propertie. Is just like that
the html for the button
input type="button" class="button tagadd" value="Add" tabindex="3"
my tries
webBrowser1.Document.GetElementById("button tagadd").InvokeMember("click");
webBrowser1.Document.GetElementById("Add").InvokeMember("click");
"GetElementById without id"
:-)
Unless you can change the markup for the button
What you need now is to traverse the entire DOM and look for a button in a known place. I'd suggest adding jquery if not already exist to be able for easier dom manipulation/search.
If you add jquery you could do something like $(".tagadd").click()
You could try doing
webBrowser1.document.getElementsByClassName("tagadd")
EDIT: Here is a script to create the getElementsByClassName function if it's not available http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/
There is also this http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.getelementsbytagname.aspx but I've never used it.
Add an ID. Even if you're dynamically generating the buttons this should be trivial.
If you're using jQuery,
$('.tagadd')
will return a collection of everything with the tagadd class applied. You can further filter this by the other classes (button, etc)
Use this:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\s)" + className + "(?:$|\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass
&& elementClass.indexOf(className) != -1
&& hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
and another
Some browsers provide the method getElementsByClassName() which lets you select by class without using jQuery (which is a bit heavy if this is all you need). I haven't tested this so I'm not sure how widely it's supported.
Did I mention that you should give everything an ID?
use TagName isteed for example
var elems = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("class") == "button tagadd")
{
elem.InvokeMember("click");
}
}

textboxes lose value on postback

i have about 4 textboxes on my webpage...some are asp:textboxes while others are input type="text".
the input textbox is populated through a javascript popup calender control while asp.net textbox is populated by typing. The initial values of these textboxes are retrieved from a database.
When a user changes these values, they are not saved and the textboxes are cleared out after the submit button is clicked. Please help resolve this confusion. Thanks.
thanks for your reply but it is still not working.....
i have put this code in my page load event
if (Page.IsPostBack)
{
if (ViewState["stock"] != null)
TextBoxMaterial.Text = ViewState["stock"].ToString();
if (ViewState["supplier"] != null)
TextBoxSupplier.Text = ViewState["supplier"].ToString();
if(ViewState["matTime"] != null)
TextBoxMatTime.Text = ViewState["matTime"].ToString();
if(ViewState["prodTime"] != null)
TextBoxProdTime.Text = ViewState["prodTime"].ToString();
if (ViewState["shipTime"] != null)
TextBoxShipTime.Text = ViewState["shipTime"].ToString();
if(ViewState["cmr"] != null)
cmrDue.Value = ViewState["cmr"].ToString();
if(ViewState["kc"] != null)
kcDue.Value = ViewState["kc"].ToString();
}
and also put the below code in the onclick event for the button
ViewState["stock"] = TextBoxMaterial.Text;
ViewState["supplier"] = TextBoxSupplier.Text;
ViewState["matTime"] = TextBoxMatTime.Text;
ViewState["prodTime"] = TextBoxProdTime.Text;
ViewState["shipTime"] = TextBoxShipTime.Text;
ViewState["cmr"] = cmrDue.Value.ToString();
ViewState["kc"] = kcDue.Value.ToString();
string prodLine = DDProdLine.SelectedValue;
string stock1 = DDMaterial.SelectedValue;
string stock2 = ViewState["stock"].ToString();
string supplier = ViewState["supplier"].ToString();
string billet = RBBillet.SelectedValue;
string matTime1 = ViewState["matTime"].ToString();
string matTime2 = DDMatTime.SelectedValue;
string prodTime1 = ViewState["prodTime"].ToString();
string prodTime2 = DDProdTime.SelectedValue;
string shipTime1 = ViewState["shipTime"].ToString();
string shipTime2 = DDShipTime.SelectedValue;
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
string format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString();
string cmr = ViewState["cmr"].ToString();
string kc = ViewState["kc"].ToString();
string x = cmr.Substring(3, 2);
string y = cmr.Substring(0, 2);
string z = cmr.Substring(6, 4);
string x1 = kc.Substring(3, 2);
string y1 = kc.Substring(0, 2);
string z1 = kc.Substring(6, 4);
string finalCmr = x + "/" + y + "/" + z;
string finalKC = x1 + "/" + y1 + "/" + z1;
DateTime dt = DateTime.ParseExact(finalCmr, format, cultureInfo);
DateTime cr = DateTime.ParseExact(finalKC, format, cultureInfo);
string custDate = dt.ToString("dd/mm/yyyy");
string kcDate = cr.ToString("dd/mm/yyyy");
string id = Request.QueryString["id"];
bool success = true;
TextBoxProdComment1.Text = stock2 + "," + supplier + matTime1 + "," + prodTime1 + "," + shipTime1 + "," + custDate
+ "," + kcDate;
try
{
success = CRTopButtons.SaveProdTable(id, prodLine, stock1, supplier, billet, matTime1, matTime2, prodTime1,
prodTime2, shipTime1, shipTime2, custDate, kcDate);
}
catch (Exception e)
{
TextBoxProdComment2.Text = e.Message;
System.Diagnostics.Trace.Write(e.StackTrace);
}
the textboxes still clear out and none of it is readonly..........
please help
I had a similar problem and The Solution to "Losing data changed by javascript during postback"
is best described by this article
ViewState and Readonly Property of Textbox
for example let's say we have this asp.net control:
<asp:TextBox ID="txtName" runat="server" EnableViewState= "false" ReadOnly="true" />
if you change the value of this control through javascript in the client side it will not be propagated via postback in the serverside...whatever you do with javascript unless you remove readonly="true". Now there is a solution to this problem as described in the article above.
Simply put this in the PageLoad event
if (!IsPostBack)
txtName.Attributes.Add("readonly","readonly");
and you're done. Just don't forget to remove ReadOnly="true" or Enable="false" if your intent was to disable the control from editing just use the snippet above. Don't forget to remove Enable="false" if you put it on.
Another thing I ran into... If you're using an ASP.NET TextBox Control (for example), and it's READONLY or DISABLED, the postback won't catch the changed value.
Per my issue, I was changing the value of the control thru javascript and even though the browser rendered the change, on the postback, the control still retained the original value.
Seems a common problem too... javascript kicks off a custom ASCX calendar control and result is injected by javascript, into the textbox. Users shouldn't be allowed to directly modify textbox value...
string strDate = Request.Form["id_of_input_element"].ToString();
I ultimately used the above to um, "reset" the control, after the postback, to it's changed value!
The <input> textboxes won't save their state after postback. ASP.NET does not handle that for you.
If you put code in your Page_Load event to set the values of the ASP.NET textboxes, the values that were posted back will not be saved, because Page_Load happens after the child control states are restored in the ASP.NET page lifecycle. The values are already restored by ASP.NET, but you are overwriting their restored values.
The correct thing to do to fix #2 is to check Page.IsPostBack before loading your initial state, like this:
if ( !Page.IsPostBack )
{
// set the textbox initial states from the database
}
UPDATE:
There are two ways to solve problem #1. One thing you could do is to use the Request.Form[] collection to retrieve the posted back value manually, like this:
string strDate = Request.Form["id_of_input_element"].ToString();
The other thing you could do, and this is what I'd recommend if you can, is to change the <input> element to an ASP.NET textbox, and hook up any client-side Javascript events to that. Then ASP.NET will completely handle your postback.
i found this when looking for an answer to the same type of problem and now that i found my problem i thought it could help someone else putting it here.
in my case i had a tag <form> inside the <form> of my controls, so, if you didnt resolve your problem with above i sugest search for a <form> lost inside your <form>.
hope it helps for some cases.
If I get you're asking for right, I think you're trying to make those textboxes readonly. If so, I had this problem before and solved it by making the textboxes readonly using C# not ASP.NET, I just added lines like textboxName.Attributes.Add("readonly", "readonly"); in the Page_Load and it worked just fine. This solution I found here on Stackoverflow
instead of TextBoxPassword.Text=Password
use
TextBoxPassword.Attributes["value"]=Password
It seems that your viewstate is disabled. Enable the viewstate in Page directive.

Categories

Resources