How to get selected value/text from HTML Select in codebehind - c#

I'm trying to get my selected value/text from and HTML select option but I can't get it! I already tried with answers posted in this website but none works.
This my code:
<select id="Select" name="Select" runat="server">
<option value="1">Option 1</option>
</select>
I tried these C# codes:
//With this I get Index out of range error message:
string name = nombre.Items[nombre.SelectedIndex].Text;
//With this I get nothing:
string name = this.nombre.Value.ToString();
//Nothing here:
string name = this.nombre.Value;
What can I do? It's necessary using html select control.

to get a value,
string sVal = dropdownName.Items[dropdownName.SelectedIndex].Value;
to get a text,
string sText= dropdownName.Items[dropdownName.SelectedIndex].Text;

You would probably be better off using an asp:DropDownList, but you can still reference straight selects. Here's code that will grab the value and text from your HTML above:
string value = Select.Items[Select.SelectedIndex].Value;
string text = Select.Items[Select.SelectedIndex].Text;
Be sure you're using the correct ID name (Select is shown in your html, but nombre is used in your code behind).

Related

How can I get the selected value from a dropdown from within a razor file in ASP.NET Core MVC

Let's say I have a view Foo.cshtml like this:
<form method="post" action="/">
<select id="Country" name="Country">
<option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
</select>
<button type="submit">Register</button>
</form>
#{
string selectedValue = ???;
string selectedText = ???;
}
How could I go about initializing these strings?
I think there is a misunderstanding over server side and client side in your code
lines below are rendered and paraphrased by server
#{
string selectedValue = ???;
string selectedText = ???;
}
it means when it reached to the browser,its done and cannot be changed
If you want to have selected value in dropdown,you should be using javascript to get what you want not server side language
you can use javascript
var e = document.getElementById("Country");
var value= e.options[e.selectedIndex].value;
var text= e.options[e.selectedIndex].text;
or get it via jquery
$('#Country :selected').text();
$('#Country :selected').val();
if I understood you correctly, you want to get the selected dropdown and pass it on to the variable below, well you could use could use javascript like so:
<form method="post" action="/">
<select id="Country" name="Country">
<option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
</select>
<button type="submit">Register</button>
</form>
var getCountry = document.getElementById("Country");
var selectedValue = getCountry.options[getCountry.selectedIndex].value;
The code below only executes once at page load to assist in rendering the HTML for your view. This is true for any C# you have in your cshtml files.
#{
string selectedValue = ???;
string selectedText = ???;
}
As other answers have noted, the way to dynamically retrieve the value of any input control is with JavaScript.
I'm assuming that after you've retrieve the selected value and text from the drop down that you'll want to use it for something in the partial view?
In which case, you'll need to use JavaScript for that as well.
//retrieve your values
var e = document.getElementById("Country");
var value= e.options[e.selectedIndex].value;
var text= e.options[e.selectedIndex].text;
//use them to do something
var targetElement = document.getElementById("your-target-elements-id");
targetElement.innerHtml = 'Text:' + text + ' Value:' + value;

Getting the HTML Markup from a dynamically constructed div

How can I get the markup for something I created like this
Div MyDiv = new Div("Test");
I essentially want to get a string with the contents
string SomeString = "<div>Test</div>";
Or maybe even
string SomeString = "<div id="MyDiv">Test</div>;
Is there any way I can do that?
One option is to give the div an id and a runat="server" attribute. If\when the page is posted back to the codebehind, use the InnerHTML property. Example:
<div id="myDiv" runat="server" />
And in your codebehind
string contents = myDiv.InnerHTML;
If you only need this data client side, use javascript, like mentioned in the comments above. You can use the following code:
var x = document.getElementById('myDiv').innerHTML;
If you already have jQuery, then:
var x = $('myDiv').html();

Using jQuery to get DDL selected value inside nested listview

I have a nested ASP.NET ListView, the outer one presenting groups of questions, and the inner one presenting distinct questions within the group. Some of the questions are presented as drop down lists. I want to detect the selected value on change without doing a postback. I have seen lots of references that look like "$(#control).val()" but I need a bit more flexibility.
I am adding the JavaScript in the C# code and it looks like this:
js = string.Format("javaScript:setInputSelectOption('{0}'); return false;", hidSelector.Value);
ddlInputSelectOptions.Attributes.Add("onchange", js);
The resultant aspx file contains this generated code;
<div id='Management_q2'>
<input type="hidden" name="ctl00$body$lstExecutive$ctrl1$hidSelector" id="ctl00_body_lstExecutive_ctrl1_hidSelector" value="Management" />
<select name="ctl00$body$lstExecutive$ctrl1$ddlInputSelectOptions"
id="ctl00_body_lstExecutive_ctrl1_ddlInputSelectOptions"
onchange="javaScript:setInputSelectOption('Management'); return false;">
<option value="0">Not Present</option>
<option selected="selected" value="1">Occasionally</option>
<option value="2">Customarily and Regularly</option>
<option value="3">Constantly</option>
</select>
</div>
My .js file contains this code:
function setInputSelectOption(question) {
var n = $('[id$=' + question + '_q2]>[id$=hidSelector]').val();
var v = $('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]');
setDDLData(n, v);
}
Using Chrome, I have tried these variants on the "var v = " line with the corresponding results:
$('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]'):
d.fn.d.init[1] $('[id$=' + question +
'_q2]>[id$=ddlInputSelectOptions]').value: undefined $('[id$=' +
question + '_q2]>[id$=ddlInputSelectOptions]').val(): ""
So I am (yet again) looking for the right incantion to utter to jQuery so that it will return the selected value from the DDL.
I would suggest keeping it simple. Add a data- attribute to the DDL you wish to get the values from. Use jQuery to find the value.
ddl.Attributes.Add("data-ddl","reference");
Then in JS.
// get value
var ddlValue = $("select[data-ddl='reference']").val();
// assign value
$("select[data-ddl='reference']").val("option");
Also, if the JS is only for UI logic, it's best to keep it out of the C# code and run it on the page ready using jQuery. So in your JS file.
$(function(){
// bind a function to the select change event
$("select[data-ddl='reference']").change(function(){
// insert UI logic here
});
});

How do I get this div tag using selenium webdriver?

<div id="ctl00_ContentHolder_vs_ValidationSummary" class="errorblock">
<p><strong>The following errors were found:</strong></p>
<ul><input type="hidden" Name="SummaryErrorCmsIds" Value="E024|E012|E014" />
<li>Please select a title.</li>
<li>Please key in your first name.</li>
<li>Please key in your last name.</li>
</ul>
</div>
I want to capture the text having value of E024 E012 and E014 and write it in to an Excel file.
I tried the following but it doesn't work.
string val1 = driver.FindElement(By.XPath("//div[contains(#class, 'errorblock'/ value = 'E024|E012|E014'")).Text;
How can I do this?
In java -
String x = driver.findElement(By.name("SummaryErrorCmsIds")).getAttribute("Value"));
Better way is to use XPATH
driver.FindElement(By.XPath("...\li")).Text; (OR)
driver.FindElement(By.XPath("...\li")).GetAttribute("value");
Your problem is you're selecting the wrong elements. I have no idea what your html looks like but try looking into FindElements and try doing a lookup by 'li'
Take a look here: Using Selenium 2's IWebDriver to interact with elements on the page
I am not sure if this is what you meant but my example solution would be:
WebElement element = driver.findElement(By.className("errorblock")).findElement(By.tagName("ul"));
List<WebElement> values = element.findElements(By.tagName("li"))
for (WebElement value : values)
{
String valueString = value.getText();
//write to excel or whatever
}
Try this:
var div = driver.FindElement(By.XPath("//div[contains(#id, 'ValidationSummary')]"));
var targetElement = div.FindElement(By.XPath("//ul[contains(#name, 'SummaryErrorCmsIds')]"));
// or var targetElement = div.FindElement(By.TagName("input"))
And then get info you need from this element.
IN C# it should be as follows.
String var1= driver.FindElement(By.XPath("//div[contains(#id, 'ValidationSummary')]")).Text;

Html Agility - Get Value by Name Tag

I need to get a value from an input, but the id always change, only the name is the same.
Didn't found anything on google to extract the value by the name tag.
Example:
<input type="hidden" name="data[_Token][key]" value="5aafaee2dd21555c2615fd26c0cccd0f1b2c3018" id="Token749368899" /></div>
I look forward to some answers.
var input= doc.DocumentNode
.Descendants("input")
.First(n=>n.Attributes["name"].Value=="data[_Token][key]");
You can try getting the first part of Id, if it's always Token#####
//input[starts-with(#id, 'Token')]
Try this
var dummy = document.getElementsByName("data[_Token][key]");
This will return you elements which has name "data[_Token][key]".

Categories