Get dropdownlist selected option from C# list of objects - c#

I have an list of objects that I receive in my Razor View in C#
#model IEnumerable<Project.Models.EvaluationObject>
In each object of the IEnumerable I have a property called "MaxValue" that I want to put selected in a input select of html.
foreach(var item in Model){
<select>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
<option value=4>Four</option>
</select>
}
For each item I want to build a select input with the value of the item.MaxValue selected
i.e. In the first loop item.MaxValue = 3, then I should build the next select:
<select>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3 selected="selected">Three</option>
<option value=4>Four</option>
</select>
The item.MaxValue is ever between 1 and 4, so If the value is 3 the selected value in the select input is 3.
The First solution I had, is to put an if statement in each option, but I think that's impractrical:
foreach(var item in Model){
<select>
<option value=1 #if(item.MaxValue==1){<text>selected="selected"</text>})>One</option>
<option value=2 #if(item.MaxValue==2){<text>selected="selected"</text>}>Two</option>
<option value=3 #if(item.MaxValue==3){<text>selected="selected"</text>}>Three</option>
<option value=4 #if(item.MaxValue==4){<text>selected="selected"</text>}>Four</option>
</select>
}
Hope you can help me, May be I should use some JavaScript.

You can add a IEnumerable<SelectListItem> to your model:
Model:
public class EvaluationObject
{
public IEnumerable<SelectListItem> EvaluationList
{
get
{
return Enumerable.Range(1, 4)
.Select(x => new SelectListItem
{
Selected = x == MaxValue,
Text = NumberToWord(x),
Value = x
});
}
}
public int MaxValue { get; set; }
public int EvaluationNumber { get; set; }
}
View:
foreach (var item in Model)
{
#Html.DropDownListFor(x => x.EvaluationNumber, item.EvaluationList)
}

Related

I can read out in my Blazor server app, the selected item of a select box. Is it also possible to read out the index number of the selected item?

With my code below I can read out the selected item in my select box (#selected_type). Is it also possible to read out something like a index number of the selected item? With index number I mean is it the first, second , third option value, of the total option values in the select list. Is that possible?
<td class="td_DiagBuff_data" max-width="150">
<select value="#selected_type" #onchange="#(e => { func_MD_type(e,index); })">
<option value="">--------</option>
<option value="">NC-Machine Data</option>
<option value="">CH-Machine Data</option>
<option value="">AX-Machine Data</option>
<option value="">DR-Machine Data</option>
<option value="">SD-Machine Data</option>
<option value="">R-Parameter</option>
<option value="">GUD</option>
</select>
</td>
Whenever I need to do this I move my <options> into a collection or dictionary of KeyValuePair with a unique identifier (If using a dictionary then Key should be the unique field).
List<KeyValuePair<string, string>> _machineDataList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>(string.Empty, "--------"), // String.Empty will force required validation attribute.
new KeyValuePair<string, string>("0", "NC-Machine Data"),
new KeyValuePair<string, string>("1", "CH-Machine Data"),
.
.
.
};
Your markup becomes
<select #bind="selected_type">
#foreach(KeyValuePair<string,string> pair in _machineDataList)
{
<option value="#pair.Key">#pair.Value</option>
}
</select>
And access the selections like this
var selection = _machineDataList.FirstOrDefault(d => d.Key== selected_type);

bind passes null when trying to pass it from select tag

I'm trying to insert data to a table which has a foreign key in it. I've put the categories in a select tag, shows them correctly, but when I try to pass that ID string to SelectedSubCatCategory, it shows up as null.
<select #bind="SelectedSubCatCategory">
#foreach (var item in category_items)
{
<option value="#item.Cat_ID" >#item.Cat_Name </option>
}
</select>
string SelectedSubCatCategory;
protected async Task SubCategoryInsert()
{
Guid guid = Guid.NewGuid();
string SubCatGUID = guid.ToString();
var category = await categoryService.GetEntryByIdAsync(SelectedSubCatCategory);
SubCategory sc = new SubCategory()
{
SCat_ID = SubCatGUID,
SCat_Cat = category,
SCat_Name = SelectedSubCatName
};
await subCategoryService.InsertEntryAsync(sc);
}
I figured it out on my own:
You have to have an #onchange event instead of #bind
<select #onchange="SetSelectedSubCatCategory">
<option> Please select </option> // default option
#foreach (var item in category_items)
{
<option value="#item.Cat_ID" >#item.Cat_Name </option>
}
</select>
And then this little code will do the rest
void SetSelectedSubCatCategory(ChangeEventArgs e)
{
SelectedSubCatCategory = e.Value.ToString();
}
gg ez

Select Option dropdown not displaying selected option

I have a Blazor app that populates 6 select option dropdowns with data from DB. Three of these are populated with date and time from a string list.
When I select a date and time it is not displayed in the dropdown box. After selecting a date time the dropdown is blank, but the value is actually selected and binding works. It's just not displayed.
If I remove "bind=#..." it displays correctly.
Have anyone else experienced this, and how did you solve it?
<select bind="#Innput.Klokkeslett1">
<option value="#(0)">Tid1</option>
#foreach (var tid1 in tidListe)
{
<option value="#tid1">#tid1</option>
}
</select>
Two things to note, select uses a string value, and that value needs to match the option value.
So, if your field Innput.Klokkeslett1 is a DateTime, you will need to use a property to handle the binding / conversion between string and DateTime.
If you ensure you use an explicit date format for the option values, and your property returns it's value in the same date format, then the select will be able to match it's value to one of it's option values and display the corresponding text, which can be formatted any way you like.
<select bind="#MySelectProxy">
<option value="#(0)">Tid1</option>
#foreach (var tid1 in tidListe)
{
<option value="#tid1.ToString("yyyy-MM-dd HH:mm:ss")">#tid1</option>
}
</select>
#functions
{
string MySelectProxy {
get => Innput.Klokkeslett1.ToString("yyyy-MM-dd HH:mm:ss");
set => DateTime.TryParse(value, out Innput.Klokkeslett1);
}
}
<select onchange="#ComboSelectionChanged">
<option value="0" selected>
#list[0]
</option>
#for (int i = 1; i < list.Count; i++)
{
<option value="#i">
#list[i]
</option>
}
</select>
public void ComboSelectionChanged(UIChangeEventArgs e)
{
if (int.TryParse(e.Value.ToString(), out int index))
{
SelectedStyleIndex = index
//now you know which one is selected
}
}

How to make a particular dropdown choice to come first

I have a drop down and elements shown in UI in order of appearance
Footer
Header
Blabla
I want the dropdown to show Header at the top position in UI.
Header
Footer
Blabla
Code UI:
<select id="simTextEditorSelection" onchange="ShowTextEditorBasedOnSelection();" style="float:right;">
#foreach (PageInfoMV anItemForEditor in Model.ItemContents)
{
<option value="#anItemForEditor.ItemId">#anItemForEditor.ItemDisplayText</option>
}
Can I somehow mention in the code above to show a particular ID as default (TOP Position).
Model.ItemContents:
public List<PageInfoMV> ItemContents
{
get
{
if (this.itemContents == null) { this.itemContents = new List<PageInfoMV>(); }
if (!this.itemContents.Any(x => x.ItemId == Constants.HEADER_ID))
{
this.itemContents.Add(new PageInfoMV() { ItemId = Constants.HEADER_ID, ItemDisplayText = Constants.HEADER_DISPLAY_TEXT });
}
if (!this.itemContents.Any(x => x.ItemId == Constants.FOOTER_ID))
{
this.itemContents.Add(new PageInfoMV() { ItemId = Constants.FOOTER_ID, ItemDisplayText = Constants.FOOTER_DISPLAY_TEXT });
}
return this.itemContents;
}
set { this.itemContents = value; }
}
Constants.cs
public static readonly string HEADER_ID = "-1000";
public static readonly string FOOTER_ID = "-1001";
Its just a code snippet. If any more code chunk is required please do let me know. Thanks.
if your Header option value is constant then you should set on top your header.
<select id="simTextEditorSelection">
<option value="Footer">Footer</option>
<option value="Header"> Header</option>
<option value="Blabla">Blabla</option>
</select>
<script>
var val1=$("#simTextEditorSelection").find('option:eq(0)').val();
$('#simTextEditorSelection option[value="Header"]').insertBefore('#simTextEditorSelectionoption[value="'+val1+'"]');
</script>
var val1=$("#simTextEditorSelection").find('option:eq(0)').val();
$('#simTextEditorSelection option[value="Header"]').insertBefore('#simTextEditorSelection option[value="'+val1+'"]');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="simTextEditorSelection">
<option value="Footer">Footer</option>
<option value="Header"> Header</option>
<option value="Blabla">Blabla</option>
</select>
If you have control over ItemContents I would suggest adding an arbitrary value to rank your contents value; For example header would be 0, footer would be 1 etc. You can then use this to do an OrderBy() in your view:
#foreach (PageInfoMV anItemForEditor in Model.ItemContents.OrderBy(ic => ic.OrderValue))
{
...
}
EDIT:
Optional additional ordering for remaining items:
#foreach (PageInfoMV anItemForEditor in Model.ItemContents.OrderBy(ic => ic.OrderValue)
.ThenBy(ic => ic.SomeOtherValueMaybeName))
{
...
}

C# Selenium: How to count elements and get selected option from a selection element

I'm using C# - Selenium Webdriver
I need to test a page that the number of selection elements is unknown. It might be one, two three... In the case example below, it contains 4 selections.
There are 2 issues here.
How to count the number of selection tags so that I can do a loop to get the selected option in each selection tags.
What's the correct syntax to get selected text with Selenium WebDriver C#?
Thank you.
<select name="ps_ck$0" id="ps_ck$0" >
<option value="A">Active</option>
<option value="C">Cancelled</option>
</select>
<select name="ps_ck$1" id="ps_ck$1" >
<option value="A">Active</option>
<option value="X">Cancelled</option>
</select>
<select name="ps_ck$2" id="ps_ck$2" >
<option value="A">Active</option>
<option value="X">Cancelled</option>
</select>
<select name="ps_ck$3" id="ps_ck$3" >
<option value="A">Active</option>
<option value="X">Cancelled</option>
</select>
You can use FindElements() method and find all select elements by tag name. For every select element found, initialize the SelectElement class instance and get the value of SelectedOption property:
IList<IWebElement> selectElements = driver.FindElements(By.TagName("select"));
foreach (IWebElement select in selectElements)
{
var selectElement = new SelectElement(select);
Console.WriteLine(selectElement.SelectedOption.Text);
}
Note that we can be more specific when locating the select elements and check the name attribute to start with ps_ck using a CSS selector:
IList<IWebElement> selectElements = driver.FindElements(By.CssSelector("select[name^=ps_ck]"));
Selenium WebDriver C# code:
SelectElement SelectEmployeeName = new SelectElement(driver.FindElement(By.Id("ps_ck$0")));
//To count elements
IList<IWebElement> ElementCount = SelectEmployeeName.Options;
int NumberOfItems = ElementCount.Count;
Console.WriteLine("Size of BGL: " + NumberOfItems);
//Getting drop down values
for(int i = 0; i < NumberOfItems; i++)
{
String DropDownItems = ElementCount.ElementAt(i).Text;
Console.WriteLine(DropDownItems);
}
//Or Loop can be written as
foreach (IWebElement i in ElementCount)
{
String DropDownItems = i.Text;
Console.WriteLine(DropDownItems);
}

Categories