How to validate the title of text box in selenium c# - c#

In my application,one of the page has more dropdown box and text box.I am tring to validate the title of each text box and dropdown box but i am unable to construct proper xpath for doing assertion.
Below is the HTML code of that text box and dropdown box.
The title of the text box and dropdown is as below:
Please Select Credit Type:
How Much Do You Need?
Loan Term
Employment Type
<div class="row">
<div class="col-md-6">
<label class="control-label" for="creditType">Please Select Credit Type:</label>
<select class="form-control" id="CreditType" name="creditType" required="" onclick="hideError(this)" onchange="onProductSelection()" onfocus="hideError(this)">
<option value="1" id="inputDivMaster-1" selected="">Personal Loan</option>
<option value="2" id="inputDivMaster-2">Credit Card</option>
</select>
</div>
<div class="col-md-6">
<label class="control-label" for="loanAmount">How Much Do You Need?</label>
<input type="text" class="form-control allownumericwithoutdecimal" id="loanAmountInput" name="loanAmount" placeholder="R500 - R249 999" pattern="\d*" maxlength="6" onclick="hideErrorById('loanAmount')" value="249999" onfocus="hideErrorById('loanAmount')">
<span class="dl-error-msg" id="loanAmountError" style="display: none;"> </span>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="control-label" for="loanTerm">Loan Term (Months)</label>
<input type="text" class="form-control allownumericwithoutdecimal" id="loanTermInput" name="loanTerm" placeholder="1 - 84 months" pattern="\d*" maxlength="2" onclick="hideErrorById('loanTerm')" value="80" onfocus="hideErrorById('loanTerm')">
<span class="dl-error-msg" id="loanTermError" style="display: none;"> </span>
</div>
<div class="col-md-6">
<label class="control-label" for="employmentStatus">Employment Type</label>
<select class="form-control" id="EmploymentStatusInput" name="employmentStatus" required="" onclick="hideErrorById('EmploymentStatus')" onfocus="hideErrorById('EmploymentStatus')"><option value="1">Permanent</option><option value="2">Temp/Seasonal/Casual worker</option><option value="3">Unemployed</option><option value="4">Pensioner</option><option value="5">Contract Worker</option><option value="6">Self Employed</option></select>
<span class="dl-error-msg" id="EmploymentStatusError" style="display: none;"> </span>
</div>
</div>
I am unable to construct xpath for locating the proper webelement to assert the title since the class name is same for all text boxes.Only the 'for' attribute gets changed.
What is the right way to locate the element.Kindly suggest suitable xpath.
String actual_title = driver.FindElement(By.XPath("_____?______")).Text;
String expected_title = "Please Select Credit Type:";
Assert.AreEqual(actual_title, expected_title);
Console.WriteLine("Text Box Title validated successfully");

You can use any attribute from the webelement as part of the xpath. In this case, you can use "for" attribute like this,
By.XPath("//label[#for='creditType']")

Related

Get specific html element when clicked

I have a web app i'm working on, and i have a foreach loop in the cshtml file to display a list of values in boxes
#foreach(var obj in Model)
{
List<double> PN = new List<double>();
PN.Add(obj.ComponentNumber);
#if (obj.ComponentNumber == 3391012471)
{
<div class="box">
<div class="parent">
<h3 class="column inline-block-column">PN - #obj.ComponentNumber </h3>
<l class="circle-comp column1 inline-block-column" style="#ViewBag.check2"></l>
</div>
<div class="">
<p class="column">物料描述 - #obj.ComponentDescription</p>
<label class="switch">
<input type="checkbox" #ViewBag.check5>
<span class="slider round"></span>
</label>
</div>
</div>
}
else
{
<div class="box">
<div class="parent">
<h3 class="column inline-block-column">PN - #obj.ComponentNumber </h3>
<l class="circle-comp column1 inline-block-column"></l>
</div>
<div class="">
<p class="column">物料描述 - #obj.ComponentDescription</p>
<label id="knob" class="switch" >
<input type="checkbox" onclick="sendmsg()" checked="checked">
<span class="slider round"></span>
</label>
</div>
</div>
}
My aim is that when the checkbox is clicked, I would like to get that specific box and change a value in it, but so far all I have tried did not work (I tried using 'getElementById' to get the box #div and change its innerHTML value, but that changed all the boxes value. I would like to be able to distinguish each box which was created using the #foreach loop)
I would appreciate guidance or suggestions from anyone on how to go about this.

Create a Condition For all non empty fields to be ReandOnly - ASP.NET Core 6.0 MVC

I am developing my first web application with ASP.NET Core 6, and I have a form that shows some fields that I already have information inside of my database.
The problem is: these fields needs to be read-only, because my user needs to considerate the information from my database. If is null, then he needs to insert a value.
Here is an example (consider the field with already set readonly). Most of fields will need this code:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<input type="text" class="form-control" placeholder="Produtos" value=""#Html.DisplayFor(model => model.iAP.Pro)" ReadOnly="readonly"/>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Dias de Utilização" />
<input type="text" class="form-control" placeholder="Valor Utilizado" />
<input type="text" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
I already build the form, and put some fields readonly with ReadOnly="readonly", but is there a way to loop all fields and put readonly with a loop or I really need to write in all fields the code `ReadOnly="readonly" ? My form is really big
But is there a way to loop all fields and put readonly with a loop or
I really need to write in all fields the code `ReadOnly="readonly" ?
My form is really big
Yes, you can set that ReadOnly attribute based on the value of your textbox field.
In this scenario you have to consider two way, either you should consider your textbox name attribute or type="text" attribute. Upon these two very way we will be decided which textbox set to readonly which is not.
For [type='text'] Attribute:
When [type='text'] means we will check all the textbox type of text and check if the textbox have value and set the readonly attribute:
View:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" name="Associado" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" name="Cota" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" name="Quantidade" class="form-control" placeholder="Quantidade" value="Test Value" />
<input type="text" name="Produtos" class="form-control" placeholder="Produtos" value="Test Value Products" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" name="Margem" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" name="Dias" class="form-control" placeholder="Dias de Utilização" />
<input type="text" name="Utili" class="form-control" placeholder="Valor Utilizado" />
<input type="text" name="Contra" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input[type='text']").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: When will will set readonly to a textbox which has value based on the text type then we have to consider like input[type='text']
For name Attribute:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: Remember in this scenario, you need to set name property for your textbox to identify uniquely as you can see I have added name property
Output:
what I understand that you want to make the input field enterable when the value of it is null. this is done by javascript.
I suggest to make all input fields read only.
use javascript to test each field, if its value is null make it enterable.
for example:
<input type="text" id="text1" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<script>
window.onload = function() {
if (document.getElementById("text1").value.length == 0)
{
document.getElementById("text1").readOnly = false;
}}
</script>
so basically when the page is loading the script will check if the input is null or not and it will do the action.

ASP.NET Core Model Binding: Using Dropdown List as Label

I am making an ASP.NET Core Mvc web app and am working on a search form. In the form, a user can be looked up by first name, last name, zip, and either ID, email, or phone. Whether a user is inputting ID, email, or phone is determined by a drop down list. I want to bind this to the User model I have but am not sure how to do it dynamically with the dropdown list. I am able to bind first name, last name, and zip just fine since they are not dynamic fields. Code for what I have so far for the form is below:
<form asp-action="Search">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label for="sel1">Search By:</label>
#* The dropdown menu to choose input type *#
<select class="form-control" id="sel1">
<option>ID</option>
<option>Email</option>
<option>Phone</option>
</select>
</div>
#* Where users would input information for the dropdown field *#
<div class="form-group">
<label for="id">Value:</label>
<input type="text" class="form-control clearable" id="id" Placeholder="0123456789">
</div>
<div class="form-group">
<label asp-for="FirstName">First Name:</label>
<input asp-for="FirstName" type="text" class="form-control clearable" id="firstName" Placeholder="Jane">
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName">Last Name:</label>
<input asp-for="LastName" type="text" class="form-control clearable" id="lastName" Placeholder="Doe">
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Zip">Zip Code:</label>
<input asp-for="Zip" type="text" class="form-control clearable" id="zipCode" Placeholder="55555">
<span asp-validation-for="Zip" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-default" id="search" />
</div>
</form>
Then the code where the model is bound on the Search function:
public async Task<IActionResult> Search([Bind("FirstName, LastName, Zip")] Consumer consumer)
{
// Code....
}
Is there a way to dynamically bind the input for the text input with id="id" based on the dropdown menu selection? Thanks in advance.
There's two options:
Render all the fields to the page (first, last, zip, etc.), and then use JavaScript to hide/show those fields based on the selection in the drop down list. For example, if you select "First Name", then show the FirstName input and hide the others. The user then enters their keywords in that input, and when they post, it will bind to FirstName naturally.
Post the value of the drop down and a generic text input. In your action, you can then simply switch on the value of the drop down and query the right property:
IQueryable<Foo> query = db.Foos;
switch (model.MyDropDownSelection)
{
case "FirstName":
query = query.Where(x => x.FirstName.Contains(keyword));
break;
// etc.
}

Form fields from the ASP.NET View appear NULL in the Controller

The form fields do not return the value of the form even thought the asp-controller and asp-action is stated.
The form does go to the right controller function and returns the right view, however, it does the form object is NULL.
#using ActionAugerMVC.Models
#model Tuple<IEnumerable<Cities>,Content,IEnumerable<Content>,Quote>
#addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"
<div class="sidebar__item">
<p class="subheading">Instant Quote Request</p>
<form class="register__form" role="form" asp-controller="Plumbing" asp-action="QuoteForm" method="post">
<div class="text-danger" asp-validation-summary="All"></div>
<div class="form-group">
<label class="sr-only">Full Name </label>
<input asp-for="#Model.Item4.FullName" type="text" class="form-control" placeholder="Full name">
</div>
<div class="form-group">
<label class="sr-only">Your phone</label>
<input asp-for="#Model.Item4.Phone" type="tel" class="form-control" placeholder="Your phone">
<span asp-validation-for="#Model.Item4.Phone" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">E-mail</label>
<input asp-for="#Model.Item4.Email" type="email" class="form-control" placeholder="E-mail">
<span asp-validation-for="#Model.Item4.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">Your Message</label>
<input asp-for="#Model.Item4.Message" type="text" class="form-control" placeholder="Your Message">
</div>
<input type="submit" value="Get a Quote Now" class="btn btn-accent btn-block">
</form>
</div> <!-- .sidebar__item -->
And the Controller looks like this, with the Quote object being null.
The hard coded, values appear correctly in the view, but the Quote object returned by the form is null.
[HttpPost]
public IActionResult QuoteForm(Quote quote)
{
if (ModelState.IsValid)
{
/* quote.FullName = "Umar Aftab";
quote.Email = "test#email.com";
quote.City = "Calgary";
quote.Message = "Test Message";
quote.Phone = "6474543769";
*/
}
return View(quote);
}
The issue is your use of a Tuple as your view's model combined with asp-for. For example, with something like:
<input asp-for="#Model.Item4.FullName" type="text" class="form-control" placeholder="Full name">
The name of the input is going to end up as Item4.FullName. However, your action accepts only Quote, which means the modelbinder needs the input to be named just FullName in order to bind it properly. You either need to accept the same model the view uses (though I've never tried posting a Tuple so not sure if that will even work), or you can use a partial view to work around the issue.
Essentially, you just would need to move all the fields related to just Quote to a partial view. Then, in this view, you can include them via:
#Html.Partial("_QuoteFields", Model.Item4)
That should be enough psych Razor out enough to just name the fields like FullName instead of Item4.FullName. If it's not, then you may need to reset the HtmlFieldPrefix, via:
#Html.Partial("_QuoteFields, Model.Item4, new ViewDataDictionary(ViewData) { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "" } })
The model on your view is different than the model you're trying to bind it to in the controller. You're not going to get the key/value pairs to match up
Put your razor in a partial view with Quote as the model and try that.
_QuoteForm.cshtml
#model Quote
<div class="form-group">
<label class="sr-only">Full Name </label>
<input asp-for="FullName" type="text" class="form-control" placeholder="Full name">
</div>
<div class="form-group">
<label class="sr-only">Your phone</label>
<input asp-for="Phone" type="tel" class="form-control" placeholder="Your phone">
<span asp-validation-for="Phone" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">E-mail</label>
<input asp-for="Email" type="email" class="form-control" placeholder="E-mail">
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">Your Message</label>
<input asp-for="Message" type="text" class="form-control" placeholder="Your Message">
</div>
OriginalView.cshtml
using ActionAugerMVC.Models
#model Tuple<IEnumerable<Cities>,Content,IEnumerable<Content>,Quote>
#addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"
<div class="sidebar__item">
<p class="subheading">Instant Quote Request</p>
<form class="register__form" role="form" asp-controller="Plumbing" asp-action="QuoteForm" method="post">
<div class="text-danger" asp-validation-summary="All"></div>
#Html.Partial("_QuoteForm", Model.Item4)
<input type="submit" value="Get a Quote Now" class="btn btn-accent btn-block">
</form>
</div> <!-- .sidebar__item -->

Firing 'click' event on input submit without ID or name?

I am trying to auto-fill a form on a webpage using .NET's web browser int he C# language. I need to fire the submit button but it doesn't have a name or ID, all it has is a type and value.
The type is equal to "submit" and the value is equal to "Sign In"
Heres how I did it for Sign Up:
webBrowser1.Document.GetElementById("email").InnerText = email;
webBrowser1.Document.GetElementById("password").InnerText = password;
webBrowser1.Document.GetElementsByTagName("input")["register"].InvokeMember("click");
But this time, the submit button doesn't have a name, can someone guide me in the right direction to getting an element by its type or even better, value?
HTML:
<form accept-charset="utf-8" method="post">
<div class="field">
<label for="email">Email or Username</label> <span class="required">*</span> <input class="email" id="email" name="email" size="32" type="text">
</div>
<div class="field">
<label for="password">Password</label> <span class="required">*</span> <input id="password" name="password" size="16" type="password">
<p class="tip">I don't know my password</p>
</div>
<div class="field">
<input id="persistent_hidden" name="persistent" type="hidden" value="f"> <input checked="checked" id="persistent" name="persistent" type="checkbox" value="t"> <label for="persistent">Keep me logged in</label>
</div>
<div class="submit">
<input id="redirect_path" name="redirect_path" type="hidden"> <input type="submit" value="Sign In"> or <a class="cancel" href="/">Cancel</a>
</div>
</form>
try :
foreach(HtmlElement elem in webBrowser.Document.getElementByTagName("input")) {
if (elem.GetAttribute("value") == "Sign In") {
elem.InvokeMember("Click");
}
}

Categories

Resources