Cant get values of inputs asp.net - c#

My problem i always get null from my inputs or default value. Some how if i set value at page_load like Form_txt_Ad.Value="ExampleValue"; i can get it. But i cant get any value from inputs.
protected void Save_Button_Click(object sender, EventArgs e)
{
string exapmle = Form_txt_Ad.Value;
string example = Form_txt_Soyad.Value;4
}
<div class="input">
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" runat="server" />
<span><i class="glyphicon glyphicon-user"></i></span>
</div>
<div class="col-md-12" style="text-align: center;">
<button type="button" runat="server" onserverclick="Save_Button_Click" class="btn btn-success btn-raised btn-lg" title="Kaydet"><i class="glyphicon glyphicon-floppy-saved icon-marginRight"></i>Kaydet</button>
</div>
Thx for help.

Make sure all your control elements are placed inside <form> ... </form> tag.
Since you have placed runat="server" you should be able to get the value by either using any of them
Form_txt_Ad.Value
(OR)
Form_txt_Ad.Text
Else use Request.Form["Form_txt_Ad"]
Not sure though why not use a server side control using <asp:TextBox ... which will allow you to get the textbox value directly using the Text property

Add the name attribute to your input and make sure it's inside a form element.
<form>
...
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" name="Form_txt_Ad" runat="server" />
...
</form>

Related

How can I check the checkbox state using Selenium?

How can I verify if a checkbox is checked or unchecked using Selenium?
Because method "element.Selected" does not work in this case.
Here is the HTML code if a checkbox is checked:
<td class="dxgvCommandColumn_MetropolisBlue dxgv" onclick="aspxGVScheduleCommand('messageGrid',['Select',1],1)" align="center">
<span id="messageGrid_DXSelBtn1_D" class="dxICheckBox_MetropolisBlue dxichSys dxWeb_edtCheckBoxChecked_MetropolisBlue">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
</td>
Here is the HTML code if a checkbox is unchecked:
<td class="dxgvCommandColumn_MetropolisBlue dxgv" onclick="aspxGVScheduleCommand('messageGrid',['Select',1],1)" align="center">
<span id="messageGrid_DXSelBtn1_D" class="dxWeb_edtCheckBoxUnchecked_MetropolisBlue dxICheckBox_MetropolisBlue dxichSys">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
</td>
Image:
As per the HTML you have shared, it's clear that the <span> tag of the outerHTML of the Checkbox contains the following class attributes:
Checked
<span id="messageGrid_DXSelBtn1_D" class="dxICheckBox_MetropolisBlue dxichSys dxWeb_edtCheckBoxChecked_MetropolisBlue">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
Unchecked
<span id="messageGrid_DXSelBtn1_D" class="dxWeb_edtCheckBoxUnchecked_MetropolisBlue dxICheckBox_MetropolisBlue dxichSys">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
So to check if the Check Box is checked or unchecked you can induce the following validation:
if(driver.FindElement(By.XPath("//input[#id='messageGrid_DXSelBtn1']//preceding::span[1]")).GetAttribute("class").contains("dxWeb_edtCheckBoxChecked_MetropolisBlue"))
Console.WriteLine("Check Box is Checked");
else
Console.WriteLine("Check Box is Unchecked");
"element.Selected" is not working, because you do not have checkbox element on the page at all. Selenium does not know that the input "looks" like checkbox. It is just HTML input of type: "text".
Your only chance is to get the JavaScript executor and check the attributes yourself (elm is your Selenium "input" object got by XPath or CSS selector):
To set the value
ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);",
new object[] {elm, "value", value });
To get the value:
ExecuteScriptReturn("return arguments[0].getAttribute(arguments[1]);",
new object[] {elm, "value" });
where the method is:
private void ExecuteScript(string script, object[] arguments)
{
var jsExecutor = (IJavaScriptExecutor)_browser;
jsExecutor.ExecuteScript(script, arguments);
}
private void ExecuteScriptReturn(string script, object[] arguments)
{
var jsExecutor = (IJavaScriptExecutor)_browser;
return (string)jsExecutor.ExecuteScript(script, arguments);
}
EDIT:
Just note you in fact are not checking the value of input in this case, but the value of class of these two elements:
span id="messageGrid_DXSelBtn1_D" class="dxICheckBox_MetropolisBlue dxichSys dxWeb_edtCheckBox**Checked**_MetropolisBlue"
and
span id="messageGrid_DXSelBtn1_D" class="dxWeb_edtCheckBox**Unchecked**_MetropolisBlue dxICheckBox_MetropolisBlue dxichSys"

How to compare database values with inputs through html form using c#

Here's the template's HTML form :
<form class="form-login" action="index.html">
<h2 class="form-login-heading">sign in now</h2>
<div class="login-wrap">
<input type="text" class="form-control" placeholder="User ID" autofocus="autofocus">
<br>
<input type="password" class="form-control" placeholder="Password">
<label class="checkbox">
<span class="pull-right">
<a data-toggle="modal" href="login.html#myModal"> Forgot Password?</a>
</span>
</label>
<button class="btn btn-theme btn-block" href="index.html" type="submit"><i class="fa fa-lock"></i> SIGN IN</button>
Here's my modification to it :
<form id="form1" runat="server" class="form-login" method="post" action="HomeDoc.aspx">
<div>
<h2 class="form-login-heading">sign in now</h2>
<div class="login-wrap">
<input type="text" class="form-control" placeholder="User ID" id="userid" runat="server" autofocus="autofocus"/>
<br/>
<input type="password" class="form-control" placeholder="Password" id="password" runat="server" />
<label class="checkbox">
<span class="pull-right">
<a data-toggle="modal" href="StaffLogin.aspx#myModal"> Forgot Password?</a>
</span>
</label>
<button class="btn btn-theme btn-block" runat="server" type="submit"><i class="fa fa-lock"></i> SIGN IN</button>
Output: So far, the page i intend to redirect the user to is being loaded every time i click the submit button, irrespective of the userid/password.
Question: What I want to do is compare the values of the 2 inputs here with the values in my SQLServer db using c#.
Also, i know the c# code for setting up connection and comparing values with db for web forms. So, what specific changes to bring to that code for html form inputs?
Please help. Thanks.
EDIT: Sorry for not providing the back end code. Here(ignore any trivial syntax error):
public partial class StaffLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login_Click(object sender, EventArgs e)
{
String getTextValuesUserID = Page.Request.Form["userid"].ToString();
String getTextValuesPassword = Page.Request.Form["password"].ToString();
//setting up connection with database
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\Pavel\\Documents\\Visual Studio 2013\\WebSites\\IMS\\App_Data\\DatabaseIMS.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Doctor where userid=#userid and password=#password", con);
cmd.Parameters.AddWithValue("#userid", getTextValuesUserID);
cmd.Parameters.AddWithValue("#password", getTextValuesPassword);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
// Response.Redirect("UserLoggedIn.aspx");
Response.Redirect("HomeDoc.aspx");
}
else
{
//javascript for invalid username and password Alert box
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and password')</script>");
}
}
}
You have multiple problems in your code, I'll point out just few of them. Before putting this site online, PLEASE, do some research on proper C# programming, because this is just plain wrong...
1.) if you use input fields with runat attribute, you can access their values in code-behind using their IDs! It's much better than to search for them in Request collection
so in your case, instead of
string getTextValuesPassword = Page.Request.Form["password"].ToString();
you can just say
string myPassword = password.Text;
2.) you should learn to close SqlConnection and dispose of external resources
3.) every time you store user's password, you SHOULD NEVER store it in plain text!!! Learn about proper hashing ASAP.
4.) you should never store connection string like this in .cs file. It can change or you may have to use it on multiple places. Store it at least in web.config
5.) .....
To address your specific problem, you are indeed comparing the values to the database values, BUT, you're not actually logging in the user. You need to do some research at least on basic Forms authentication, or if you need a more advanced scenario, you can use ASP.NET Identity.

How to get Textbox control in C#

I have a HTML textbox
<script>
$(function () {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true
});
});
</script>
<input type="text" size="10" name="datepicker" id="datepicker" />
Now i need to set the value of textbox to "abcd";
I tried datepicker.Text = "abcd"; Error is "the name datepicker does not exist in current context"...
I tried finding the Control and assigning the value but still could not do it.
Is there any other way to do it??
Thanks
You'll first need to make your <input> control a server side tag, using the runat="Server" attribute:
<input runat="server" type="text" size="10" name="datepicker" id="datepicker" />
Then, you can modify the value using C# code:
protected void Page_Load(object sender, EventArgs e)
{
datepicker.Text = "New Value"; // Initial value for input field
}
If you want to modify the value on the client side, using jQuery, I'd first suggest making the ID static:
<input runat="server" ClientIDMode="Static" type="text" size="10" name="datepicker" id="datepicker" />
Then you can do:
$("#datepicker").val('New Value');
Anywhere after the page has been loaded.

File Upload using Twitter Bootstrap, C#, asp.net and javascript

link to Jasny http://jasny.github.com/bootstrap/javascript.html#fileupload
link to what the form looks like http://img507.imageshack.us/img507/3308/picpx.png
I am using the Jasny Javascript file upload in my boot strap project, it looks like this:
ASP\HTML VIEW
<div class="row-fluid">
<div class="fileupload fileupload-new" data-provides="fileupload"><input type="hidden">
<div class="input-append">
<div class="uneditable-input span2" runat="server" id="statment1"><i class="icon-file
fileupload-exists"></i> <span class="fileupload-preview" style=""></span></div><span
class="btn btn-file"><span class="fileupload-new">Select file</span><span
class="fileupload-exists">Change</span><input type="file"></span><a href="#" class="btn
fileupload-exists" data-dismiss="fileupload">Remove</a>
</div>
</div>
How do I go about using this in the code behind to save the attached file to my server as I would using the C# asp.net File Upload?
In ASP.net C# I would normally do this in the code behind:
ASP.net C# CodeBehind
string filename = FileUpload1.PostedFile.FileName;
FileUpload1.PostedFile.SaveAs(Path.Combine(Server.MapPath("\\Document"),
filename).ToString());
filelocation = "Document\\" + filename;
media = "Document";
The Jasny github explains how to set the layout using bootstrap which is great as it looks really good (much better than the boring asp file upload) but How do I actually get I to post on my button click? I would really like to get this to work as I think it looks heaps nicer.
Since you want to do this without a standard asp.net control, you will have to do some of the wiring that asp.net does for you.
Make sure your input has an id. I will set it here to myFile.
<div class="row-fluid">
<div class="fileupload fileupload-new" data-provides="fileupload"><input type="hidden">
<div class="input-append">
<div class="uneditable-input span2" runat="server" id="statment1">
<i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview" style=""></span>
</div>
<span class="btn btn-file"><span class="fileupload-new">Select file</span>
<span class="fileupload-exists">Change</span><input id="myFile" type="file" runat="server">
</span>
<a href="#" class="btn fileupload-exists" data-dismiss="fileupload" >Remove</a>
</div>
</div>
</div>
Your page should now have a HtmlInputFile control to your page. like this:
protected HtmlInputFile myFile;
Then you should be able to receive the file:
if (IsPostBack)
{
if (myFile.PostedFile != null)
{
// File was sent
var postedFile = myFile.PostedFile;
int dataLength = postedFile.ContentLength;
byte[] myData = new byte[dataLength];
postedFile.InputStream.Read(myData, 0, dataLength);
}
else
{
// No file was sent
}
}

Accessing <div> from both javascript and code-behind

I have a div with style="display:none". The div should become visible on pressing an html button:
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
<div style="float:left">
<div id="ctl00_MainContent_upnlLbRD">
<select size="4" name="ctl00$MainContent$lbRD" id="ctl00_MainContent_lbRD" style="width:188px;">
<option value="5">one</option>
<option value="1">two</option>
</select>
<input id="btnAdd" type="button" value="Добавить" onclick="JSAdd();" />
<input id="btnEdit" type="button" value="Редактировать" onclick="JSEdit();" />
</div>
<div id="ctl00_MainContent_divDetail" style="display:none" clientidmode="static">
<div id="ctl00_MainContent_upnlDescription">
<div>
<span id="ctl00_MainContent_lblDescription">Описание:</span>
<input name="ctl00$MainContent$txtDescription" type="text" id="ctl00_MainContent_txtDescription" />
<span id="ctl00_MainContent_txtDescriptionRequiredFieldValidator" style="color:Red;visibility:hidden;">Описание является обязательным для заполнения</span>
</div>
<input type="submit" name="ctl00$MainContent$btnSave" value="Сохранить" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$btnSave", "", true, "", "", false, false))" id="ctl00_MainContent_btnSave" />
I need to be able to make the div invisible again from code-behind. I cannot access the div unless it is runat="server". But when I add runat="server", the div doesn't become visible on pressing the button from the javascript function above. Could you please help me with this?
Thanks,
David
You can access a div in code-behind by adding the runat="server" attribute. Adding this attribute does change the way you access the element in JavaScript though:
var el = document.getElementById("<%=div1.ClientID%>");
if (el){
el.style.display = "none"; //hidden
}
There are two ways to adjust the visibility from code-behind, but since you're setting display:none in JavaScript, you'd probably want to use the same approach in code-behind:
div1.Style["display"] = "block"; //visible
In code-behind, you can also set the Visible property to false, but this is different because it will prevent the element from being rendered at all.
EDIT
If the div is still showing with display:none present, you probably have an unclosed tag or quote somewhere affecting the markup. Double check and make sure that the markup is valid.
Use a Panel, it renders as a classic div
<asp:Panel runat="server" ID="divDetail" ClientIDMode="Static" />
You have a few options, use ClientIDMode="Static" or use the dynamic ClientID at run-time. Both of these options give you server-side access to the object.
Dynamic:
<div id="divDetail" runat="server" />
//or
<asp:panel id="divDetail" runat="server" />
function JSAdd() {
document.getElementById('<%= divDetail.ClientID %>').style.display = "block";
}
//to hide from code-beind
divDetail.Attributes.Add("style","display:none;");
Static(.NET 4.0 +):
<div id="divDetail" runat="server" ClientIdMode="Static">
//or
<asp:panel id="divDetail" runat="server" ClientIdMode="Static" />
function JSAdd() {
document.getElementById('divDetail').style.display = "block";
}
When runat="server" is applied to an element, asp.net ensures that it has a unique ID by mangling it. Simply ask asp.net for the real client id:
function JSAdd() {
document.getElementById("<%=div1.ClientID%>").style.display = "block";
}
Alternatively, you could tell asp.net to leave your ID alone by adding this to your div:
<div id="div1" runat="server" clientidmode="Static">
Resources:
ClientIdMode="Static" docs
In ASP.NET, to make IDs unique (if multiple control loaded where same ID are specified), ID on elements are often follow a convention like ctl00_container1_container2_controlID and this is what returned when you call control.ClientID.
If you consider such a case where there's same ID on the serverside and you loaded those two controls in your page, you may consider using jQuery and life would be easier with runat="server" with just matching the ID with the end part:
function JSAdd() {
$("div[id$=divDetails]").show();
}
Simplest technique will be to use Javascript/Jquery to Changes Display property of the Div. if not that you can use following code
<form method="post" runat="server">
<div style = "display:none" id= "div1" runat ="server" >Hello I am visible</div>
<asp:Button Text="display Div" runat ="server" ID ="btnDisplay" OnClick = "displayDiv" />
<asp:Button Text="display Div" runat ="server" ID ="btnHideDiv" OnClick = "hideDiv" />
</form>
code behind code is as follows
protected void displayDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "block");
}
protected void hideDiv(object sender, EventArgs e)
{
div1.Style.Clear();
div1.Style.Add("display", "none");
}
guess you Got your solution

Categories

Resources