I'm trying to get values of input element which generated with ko.toJS using Selenium in Firefox:
<input autocomplete="on" class="form-control input-block-level " data-bind="value: $data.Reciever().LastName , disable: !$root.Actions.AllowChange()" data-code-in="false" data-fildid="945" data-param-getall="False" data-povalue="true" id="Reciever_LastName" name="Reciever.LastName" type="text" value="" disabled="" required="">...
JS code looks like this:
$(function () {
window.DocMVVM = new UMT_Payout_MoneyMVVM(ko.toJS(
{"Sender":{"LastName":"ABC","FirstName":"BCA","Patronymic":"DEF"},
"Reciever":{"LastName":"GHI","FirstName":"IHG","Patronymic":"JKL"},...
I tried by CssSelector
driver.FindElement(By.CssSelector("input.form-control.input-block-level[id='Reciever_LastName']")).GetAttribute("value")
but the result is NULL.
Is anybody had such kind of task and how could I get values of inputs?
Thanks.
To retrieve the value attribute from the <input> element you have to induce WebDriverWait for the ElementIsVisible() and you can use either of the following Locator Strategies:
CssSelector:
Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input.form-control.input-block-level#Reciever_LastName[name='Reciever.LastName']"))).GetAttribute("value"));
XPath:
Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[#class='form-control input-block-level ' and #id='Reciever_LastName'][#name='Reciever.LastName']"))).GetAttribute("value"));
Related
In my asp.net core 3.1 I have method which I am returning back aws intance type list and I am consuming api in my angular 8 project.
When I use postman I am getting back json result as
[
"c5n.4xlarge",
"m2.2xlarge",
"t3.xlarge",
"m5dn.8xlarge",
..........
]
But in network tab in chrome I am getting response back
And when I try to post (it works in backend) It throws error
Input string was not in correct format
I see it does not grab value and sets to undefined. How to make json result similar to postman result not numbered. No idea that is the reason or not. But in response section it is normal json. Maybe it is multiple arrays that is the reason.
P.S. Also looked another topics about Input string was not in correct format but it was related with integer issue but in my case I need just string
My service: // it is also similar method for opentack and it works fine
createAws(model: any, projectId: number, instanceType?: any) {
return this.http.post(`${this.baseUrl}servers/${projectId}?i
instanceType=${instanceType}`, model);
}
My component: //
selectInstanceHandler(event: any){
this.selectedInstance = event.target.value;
}
createAws(instanceType: any){
this.subs.add(this.cvmService.createAws(this.model,this.projectId,instanceType).subscribe(
x => {
this.model = x;
this.alertify.success("successfully added new Server");
},
error => {
this.alertify.error("\n" + error);
}
))
}
My html:
<div class="row" *ngIf="type == 'AWS'">
<div class="col-3 mt-3 labelText">
<span class="spanText">Aws Instance Type</span>
</div>
<div class="col-9">
<mat-form-field class="example-full-width">
<mat-label>Please select intance type</mat-label>
<select matNativeControl required name="awsInstanceType"
[(ngModel)]="model.awsInstanceType"
(change)="selectInstanceHandler($event)">
<option value="-1" disabled> </option>
<option *ngFor="let item of aws">
{{ item }}
</option>
</select>
</mat-form-field>
</div>
</div>
Example in postman which works:
{{url}}/api/servers/22?instanceType=r5a.large
The result is not numbered, it is just chrome's way of formatting data to make it easy to read. That is why it is known as preview tab.
Check the response tab, the response is just the array of strings (i.e. not numbered)
Currently redeveloping a part of the site, and I'm struggling to get some of the new asp.net features to line up with legacy code.
In particular, one of the forms has been changed to use the asp-for attribute:
<div class="form-group label-floating col-lg-6 col-xs-12">
<input asp-for="#this.Model.SearchFilters.Surname" class="form-control" placeholder="#(page.Labels["Surname"].Content.Term)" aria-label="#(page.Labels["Surname"].Content.Term)" />
</div>
<div class="form-group label-floating col-lg-6 col-xs-12">
<input asp-for="#this.Model.SearchFilters.Firstname" class="form-control" placeholder="#(page.Labels["Forenames"].Content.Term)" aria-label="#(page.Labels["Forenames"].Content.Term)" />
</div>
This generates a querystring like so:
?SearchFilters.Surname=bob&SearchFilters.Firstname=tway
In a controller action down the line, a path back to this page is generated with Url.Action:
Url.Action(
nameof(this.MyMethod),
new { viewModel.SearchFilters.Firstname, viewModel.SearchFilters.Surname });
But that generates a querystring without the SearchFilters prefix:
?Surname=bob&Firstname=tway
Since that doesn't match the expected model, the generated Url results in a server error.
I've tried to change the Url.Action to specify the name like so:
Url.Action(
nameof(this.MyMethod),
new { SearchFilters.Firstname = viewModel.SearchFilters.Firstname, SearchFilters.Surname = viewModel.SearchFilters.Surname });
But this won't compile, saying it's an "Invalid anonymous type member declarator".
In an ideal world I'd like to change the Url.Action to include the prefix, but I can't work out how this is done. I'd settle for removing the prefix generated by asp-for, as I change the model if need be. Either way, how do I bring these two Querystrings into line?
You can specify a parameter name with a period by using a RouteValueDictionary instead of an anonymous object.
Url.Action(
nameof(this.MyMethod),
new new RouteValueDictionary { { "SearchFilters.Firstname", viewModel.SearchFilters.Firstname }, { "SearchFilters.Surname", viewModel.SearchFilters.Surname } });
Picture In Response to a Answer
What The Webpage looks Like
<input name="ftitle" class="inputbox ui-autocomplete-input" type="text" autocomplete="off">
I need to add value= to the above HTML input element
How do I go about doing this? For the life of me, I can Not Figure it out.
Edit: I need this because I need to fill in a text box that is on a web page that does not contain the value= in it. But if I right click on it and add attribute value= then I can change the text through my program.
I am using C# web browser control so I'm using
HtmlElement NewAttribute = doc.GetElementById("ftitle");
So when everything is said and done it will look like this.
<input name="ftitle" class="inputbox ui-autocomplete-input" type="text"
autocomplete="off" value="">
Here what I got so far if it helps to see what I am up to. this is all for a different web page but I am doing the same thing but I need to add the class "value"
private void Generate_Click(object sender, EventArgs e)
{
HtmlDocument doc = wbNewProject.Document;
HtmlElement wbJobName = doc.GetElementById("Name"); //lblcontact.text
HtmlElement wbEngineer = doc.GetElementById("engineer-lookup"); //
HtmlElement wbSalesEng = doc.GetElementById("SalesEngineerUserId");
HtmlElement wbLocation = doc.GetElementById("Location");
HtmlElement wbBidDate = doc.GetElementById("BidDate");
HtmlElement wbPriorApproval = doc.GetElementById("PriorApproval"); //True or False
HtmlElement wbTakeOff = doc.GetElementById("TakeOffComplete"); //True or False
HtmlElement wbProject = doc.GetElementById("RoleType"); //Design/Build or Plan/Spec
HtmlElement element = wbNewProject.Document.GetElementById("ftitle");
try
{
wbJobName.SetAttribute("value", lblJobName.Text);
if (lblContact.Text.Contains("Dan"))
wbSalesEng.SetAttribute("value", "2");
if (lblContact.Text.Contains("Kelley"))
wbSalesEng.SetAttribute("value", "3");
if (lblContact.Text.Contains("Erv"))
wbSalesEng.SetAttribute("value", "4");
if (lblContact.Text.Contains("Marc"))
wbSalesEng.SetAttribute("value", "5");
if (lblContact.Text.Contains("Terry"))
wbSalesEng.SetAttribute("value", "6");
if (lblContact.Text.Contains("Chad"))
wbSalesEng.SetAttribute("value", "7");
if (lblContact.Text.Contains("Jacob Lenertz"))
wbSalesEng.SetAttribute("value", "10");
if (lblContact.Text.Contains("Terry"))
wbSalesEng.SetAttribute("value", "11");
if (lblContact.Text.Contains("Nate"))
wbSalesEng.SetAttribute("value", "12");
wbLocation.SetAttribute("value", lblLocation.Text);
wbBidDate.SetAttribute("value", lblBidDate.Text);
if (lblPriorApp.Text.Contains("Yes"))
wbPriorApproval.SetAttribute("value", "true");
if (lblPriorApp.Text.Contains("No"))
wbPriorApproval.SetAttribute("value", "false");
if (lblTakeOff.Text.Contains("Done"))
wbTakeOff.SetAttribute("value", "true");
if (lblTakeOff.Text.Contains("Not Done"))
wbTakeOff.SetAttribute("value", "false");
wbEngineer.SetAttribute("value", lblEngineer.Text);
wbProject.SetAttribute("value", lblProject.Text);
}
catch { }
}
Javascript
document.getElementById(elementName).value = "your value";
jQuery
$('#elementName').val() = "your value";
Both approaches will require you to create an Id on your element. However, jQuery will also allow you to select your element by other means other than an Id.
Web forms c#
This is also simple, use the SetAttribute Method:
HtmlElement element = doc.GetElementById("ftitle"); //Your have this, correct?
element.SetAttribute("value", "your value");
You could do this incredible hokey approach:
$(document).ready(function() {
var title = #model.Title;
$('[name="title"]').val(title);
});
You can also implement Razor directly:
<input type="text" value="#model.Title" />
Keep in mind though, if #model is null, you'll receive an application error. But as denoted it is an approach. The approach I would honestly take, would be a JavaScript template, then parse my data model directly to the template, then append the template directly into the View State.
How can I get the value of a textbox using razor?
<div>
<input type="text" id="somevalue" name="somevalue" class="form-control"/>
<input type="button" value="Search" class="btn btn-success"/>
</div>
<ul id="ReportsList" class="nav">
#foreach (var item in Model){
var roomName= document.getElementByID('somevalue').value
if (item.roomName == roomName) {
<li class="errorItem">
<a href="#" class="list-group-item">
<i class="fa fa-warning fa-fw"></i> #Html.DisplayFor(modelItem => item.roomName)
<span class="pull-right text-muted small">#Html.DisplayFor(modelItem => item.roomCapacity) pers.
</span>
..........
}
Is it possible to get the value of the textbox using MVC Razor? Cause using the getElementByID doesn't seem to work in razor...
Don't be brought down by the down-ticks.
You are obviously new to Razor and Mvc & Javascript. You problem is that you are mixing a server-side language with a client-side language. Razor is a server-side language so you will not be able to access client-side code (ie html or javascript) using Razor. Razor is used to render html to the client browser. Think of the code that you see in a cshtml file as a template for the code that will become an html file. The javascript on the other hand will only run when it gets to the users browser.
Now, lets try to make some sense of your code.
<div>
<input type="text" id="somevalue" name="somevalue" />
<input type="button" value="Search" />
</div>
<ul id="ReportsList" class="nav">
#foreach (var item in Model)
{
var roomName= document.getElementByID('somevalue').value; // This is javascript code.
if (item.roomName == roomName) {
<li>
#Html.DisplayFor(modelItem => item.roomName)
#Html.DisplayFor(modelItem => item.roomCapacity)
</li>
}
}
</ul>
I removed the classes to make it more legible. The problem above is that you are trying to find a value to use with your razor code. That code is running before it gets to the browser so that won't work.
You cannot solve this problem using Razor. That means your DisplayFor's are going to be useless for your scenario.
You need javascript to solve the problem, so you will need to do away with the Razor Code. Assuming your Model has as list of object with the properties you created in your example, you could do something like this.
<script type="text/javascript">
var data = #(Html.Raw(Json.Encode(Model));
for(var o in data) {
var item = data[o];
// You need to create an element here and add it to the ul here
// You could use jquery.
}
</script>
Unfortunately, you have the wrong tools here.
To actually accomplish what you are trying to do you are going to be better off investing in some javascript frameworks. I suggest that you learn AngularJs to do this.
Concerning Organization of Javascript
As stated in the comments you can use a script tag in your cshtml file. Unfortunately, this is not your problem. I added a little bit of a way to organize your javascript as well.
your.cshtml file.
<script type="text/javascript">
.. getElementById in here and do something.
</script>
Better Organization Might Look Like This
Put the code in a javascript file. In this example the name is person.js. I am using a person example because it is an easy way to look at creating an usable object in javascript. In this case person is the object.
person.js
function Person() {
}
Person.prototype = {
// Sets the element with id = "nameId" to "Jim Bob"
setName: function() {
var element = document.getElementById("nameId");
// Now do something with it.
element.innerHTML = "Jim Bob"; // get some user input.
}
};
// You could initialize this as a global reference.
// I don't recommend this but it will be the easiest way for now.
var person = new Person();
Next, you would have to use it somehow. The simplest way to use it is not the best way.
<button id="setNameButton" onclick="person.setName()">Set Name</button>
Improved example using JQuery
This example will bind the event in an unobtrusive way (ie. you won't be mixing javascript and html).
function Person() {
this.initialize();
this.name = "Jim Bob";
}
Person.prototype = {
initialize: function() {
// get reference to this object.
var self = this;
// Set up the click for button.
$(document).on('click', "#setNameButton", function() {
// Set the name
self.setName();
});
}
// Sets the element to this.name field.
setName: function() {
var element = document.getElementById("nameId");
// Now do something with it.
element.innerHTML = this.name;
}
};
My content will be edited number of times.So i need to store result html to database and load it again when it is neccessary.Here is my current start implementation:
#using (#Html.BeginForm("EditArticle", "Admin", new { id = ViewData["id"] }))
{
<div id="editor"> </div>
<input type="submit" value="save changes" onclick = "setValue()" />
<input type ="hidden" id="value" name="html" />
}
<script>
var editor, html = 'Model.Text';
function createEditor() {
if (editor)
return;
var config = { width:"900px"};
editor = CKEDITOR.appendTo('editor', config,html);
}
function setValue() {
$("#value").val(editor.getData());
}
createEditor();
</script>
But I get eror with initialization html variable.So, could anyone show how correct encode / decode html?
EDIT
Here is data controller receives:
html = <p>ARTICLE 3</p>\r\n
Values like this I store in database and try insert again.
First things first, to fix your code syntactically, it should probably read something like:
var editor, html = '#Html.Raw(Model.Text)';
However, why not instead of dealing with the markup in JavaScript and having to escape and unescape it, dump it directly where it should go i.e.
<textarea name="editor1">#Html.Raw(Model.Text)</textarea>
<script>
CKEDITOR.replace( 'editor1' );
</script>
And then transform that textarea into your ckEditor? As per their basic example here: http://docs.ckeditor.com/#!/guide/dev_framed
Secondly, aside from that I am not sure what errors you are receiving with your controller, so you will have to post further details for me to help you beyond the above.
I hope this helps.