html helpers for dropdown lists? - asp.net-mvc

Are there any helpers for displaying dropdownlists in asp.net-mvc?
I have an enumeration that I need to populate, and pre-select in a dropdownlist.

The FluentHtml library from MVC Contrib has built-in support for generating select boxes from enumerations.
<%= this.Select("example")
.Options<System.IO.FileOptions>()
.Selected(System.IO.FileOptions.Asynchronous) %>
This outputs:
<select id="example" name="example">
<option value="0">None</option>
<option value="16384">Encrypted</option>
<option value="67108864">DeleteOnClose</option>
<option value="134217728">SequentialScan</option>
<option value="268435456">RandomAccess</option>
<option selected="selected" value="1073741824">Asynchronous</option>
<option value="-2147483648">WriteThrough</option>
</select>

<%= Html.DropDownList() %> has about 8 overloads that you can use. You'll need to map your enumeration into an IEnumerable<SelectListItem> to pass to it though. Something like this:
var names = Enum.GetNames(typeof(MyEnum));
List<SelectListItem> items = new List<SelectListItem>();
foreach (var s in names)
{
items.Add(new SelectListItem() { Text = s,
Value = s,
Selected = (s == "SelectedValue") };
}

Related

Multiselect grouping programmatically - MVC

I have a table in this format:
table format
And i try to get this result programmatically:
desired result
I'm using asp.net mvc with razor.
I know there is an example here but i couldnt adapt in my situation :(
May you give an example please?
ADDED my work:
I think i must get the records via json, am i wrong? and im not good at in json
<script type="text/javascript">
$('#ddl_Hours').multiselect();
</script>
<select id="ddl_Hours" multiple>
#foreach (myModel item in ((MultiSelectList)ViewBag.MyList).Items)
{
int dayID = 0;
if (dayID != item.DayID )
{
<optgroup label="#item.DayID ">
<option value="#item.HourID">#item.Name</option>
</optgroup>
}
dayID = item.DayID;
}
</select>
Controller:
var list = (from p in db.T_MYTABLE
select new MyModel { HourID = p.HourID ,
DayID = p.DayID,
Name = p.Name
}).ToList();
ViewBag.MyList= new MultiSelectList(list, !string.IsNullOrEmpty(selectedValue) ? selectedValue.Split(',').ToArray() : null);
For generating such a grouped multi select using the jQuery plugin, first you need to render the HTML markup for grouped options like below
<select id="ddl_Hours">
<optgroup label="4">
<option value="1">00.00</option>
<option value="2">01.00</option>
<option value="3">02.00</option>
<option value="4">03.00</option>
</optgroup>
<optgroup label="2">
<option value="5">04.00</option>
<option value="6">05.00</option>
<option value="7">06.0</option>
</optgroup>
<optgroup label="3">
<option value="8">07.00</option>
<option value="9">08.00</option>
</optgroup>
</select>
To generate the above markup in your view, you can create a list of item's in your action method with the Group property.
var list = db.T_MYTABLE.ToList();
//Create a list of Groups
var groups = list.Select(x => x.DayId)
.Select(f => new SelectListGroup() { Name = "Day " + f.ToString() }).ToList();
var groupedOptions = list.Select(x => new SelectListItem
{
Value = x.HourId.ToString(),
Text = x.Name,
Group = groups.FirstOrDefault(a => a.Name == "Day " + x.DayId.ToString())
}).ToList();
ViewBag.MyList = groupedOptions;
return View();
Assuming Name property of your entity is string type. If it is numeric type, use the ToString() method when setting the Text property value in the projection part of the above linq query (Text=x.Name.ToString())
Now in your razor view, you can use the Html.DropDownList helper method to render the SELECT element.
#Html.DropDownList("ddl_Hours", ViewBag.MyList as List<SelectListItem>)
or for the multi select
#Html.ListBox("ddl_Hours", ViewBag.MyList as List<SelectListItem>)
Now you can call your jQuery plugin to make it fancy. I would call it inside the document's ready event
$(function () {
$('#ddl_Hours').multiselect();
})
and Voila!

Attribute selected in option is deleted on HTML using Razor on asp.net-core-mvc

I'm trying to add the attribute selected to an option inside a select, something like: <option value="item" selected>item</option>, but in an strange event the text selected is deleted when rendering the page.
For example I have the following code:
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<option
value="#str"
#sel>
#str
</option>
}
</select>
In this if searchCode == str then the #sel is set as "selected" but the problem is that when the site is rendered the #sel attribute is not printed.
For example, it should print:
<select>
<option value="a">a</option>
<option value="b" selected>b</option>
<option value="c">c</option>
</select>
But instead it prints:
<select>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
If I change my code to this:
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<option
value="#str"
#sel>
#str - #sel
</option>
}
</select>
I'll get something like this:
<select>
<option value="a">a - </option>
<option value="b">b - selected</option>
<option value="c">c - </option>
</select>
So the attribute selected is correctly calculated but it's not printed as it should.
Any ideas on what's happening?
It appears to be a bug: https://github.com/aspnet/Mvc/issues/3733
What I did is to change option as !option.
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<!option
value="#str"
#sel>
#str - #sel
</!option>
}
</select>
1) create class for search criteria
public class SearchCriteria
{
public string searchCode { get; set; }
public List<string> results { get; set; }
}
2) add the default option before binding the list
var searchCriteriaObj = new SearchCriteria { searchCode = "bla bla bla" };
searchCriteriaObj.results = searchManager.getResults(searchCode);
searchCriteriaObj.results.Insert(0, " Nothing Selected");
3) bind the object by passing it (Controller) after getting the results.
ViewBag.criteria = searchCriteriaObject;
4) View page:
<select asp-for="ViewBag.criteria.searchCode"
asp-items="ViewBag.criteria.results">
</select>

mvc razor dropdown list

I want to know how to put drop down list like this:
<div>
<label>Price Range</label>
<select>
<option value="1">min</option>
<option value="50000">50,000</option>
<option value="100000">100,000</option>
<option value="150000">150,000</option>
</select>
in the view , and read the selected parameter in the controller
tnx
There are many ways to make it work.
Its depend on your needs.
I am going to show you the simplest way to create it in the view itself
You can do it like this all inlined in your *.cshtml file like so:
#{
var loadListItems = new List<SelectListItem>();
loadListItems.Add(new SelectListItem { Text = "text1", Value = "value1", Selected = true });
loadListItems.Add(new SelectListItem { Text = "text2", Value = "value2" });
}
//Begin Form
#Html.DropDownList("ListKey",loadListItems);
//End Form
Will produce the result as follows:
<select name="ListKey">
<option value="value1">text1</option>
<option value="value2">text2</option>
</select>
And on submitting it on controller side you can get the values as follows:
ActionResult YourActionName(FormCollection collection){
var selectedValue = collection["ListKey"];
}

Set selected value of a dropdown in Razor view

I am trying to set the selected value in a dropdown in a razor view.
<select id="drpStatus" name="status">
<option value="A">Active</option>
<option value="S">Suspended</option>
<option value="T">Terminated</option>
<option value="D">Deleted</option>
</select>
//I am trying with the below code, based on the value in Model, I want to set the particular option as selected
<option selected=#{if(#Model!=null && #Model.Status=='A'){'selected'}} value="A">Active</option>
Above code is not working, please let me know if I am working in a right direction or is there any other/better way to achieve it.
Try this from your controller
Controller :
var record = db.Records.Find(id);
ViewBag.DropStatus = new SelectList(ListOfStatus, record.Status);
The first parameter for SelectList should be an IEnumerable which will serve as the data source for your DropDownList, the second parameter is for the selected value, so just pass the status property of the record you want to edit.
View:
#Html.DropDownList("Status", string.Empty)
The first parameter is the name of the ViewBag we assigned in the controller, it will also serve as the name when you post the data. Hope I've made myself clear.
The following is one of some possible solutions
#{
ViewBag.Title = "Index";
Func<char, MvcHtmlString> function = (c) => Model != null && Model.Status == c
? MvcHtmlString.Create("selected='selected'")
: MvcHtmlString.Empty;
}
<h2>Index</h2>
<select id="drpStatus" name="status">
<option #function('A') value="A">Active</option>
<option #function('S') value="S">Suspended</option>
<option #function('T') value="T">Terminated</option>
<option #function('D') value="D">Deleted</option>
</select>
It would be better to use SelectList in your ViewModel.
Another possible solution is using Razor's helper tag in the cshtml:
#helper SetGender(string dropdownvalue)
{
var selected = string.Format("value=\"{0}\"", dropdownvalue);
if ((string.IsNullOrEmpty(dropdownvalue) && string.IsNullOrEmpty(User.GetClaim(ClaimTypes.Gender.ToString()))) ||
(User.GetClaim(ClaimTypes.Gender.ToString()) == dropdownvalue))
{
selected = string.Concat("selected='selected' ", selected);
}
#Html.Raw(selected);
}
<select name="gender">
<option #SetGender("") >-not set-</option>
<option #SetGender("male") >male</option>
<option #SetGender("female") >female</option>
</select>
#{
List<SelectListItem> lstOrderTypes = new List<SelectListItem>();
lstOrderTypes.Add(new SelectListItem {Value = "1", Text = "plan1" });
lstOrderTypes.Add(new SelectListItem {Value = "2", Text = "plan2" });
}
#functions {
public static string GetString(IHtmlContent content)
{
var writer = new System.IO.StringWriter();
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
#{
var x = GetString(Html.DisplayFor(model => model.OrderType));
}
<select>
#foreach (SelectListItem option in lstOrderTypes)
{
<option value="#option.Value" selected="#(option.Value == x)">#option.Text</option>
}
</select>

MVC .Net MultiSelectList does not mark values

I have a simple problem, that I don't have with SelectList!
I just wan't to pre-select entries in MultiSelectList and here is my simple code:
List<Language> lLang = new List<Language>
{
new Language { Abbreviation = "DE", Name = "German" },
new Language { Abbreviation = "IT", Name = "Italian" }
};
ViewBag.Languages = new MultiSelectList(lLang, "Abbreviation", "Name", new string[] { "DE", "IT" });
In order that you see, that the values are actually correct, here the rendered HTML code:
<select id="Languages" name="Languages" multiple="multiple">
<option value="AF"> … </option>
<option value="AR"> … </option>
<option value="DA"> … </option>
<option value="DE"> … </option>
</select>
As you see, the option value "DE" is not selected!
Any ideas?!
Thanks in advance!

Resources