I have a Drop Down List in my MVC application, which is populated from my "PropertyList" model.
I have set the propertyList variable as follows to obtain the details needed for each option as follows;
var propertyList = new SelectList(Model.propertyList, "fullPropertyDetail", "FullAddress");
#Html.DropDownList("addresslist", (SelectList)propertyList, "-- Please select an address from the list below --", new { #id = "valid-addresslist" })
This populates the list as expected and the default option reads "-- Please select an address from the list --", however the value for that option is set as "".
Is there any way I can set the default option value as "none" as another system looks for this value if it is selected.
Simply you can do as follows:
#{
List<SelectListItem> selectListItems = propertyList.ToList();
selectListItems.Insert(0, (new SelectListItem { Text = "Please select", Value = "none", Selected = true }));
}
#Html.DropDownList("addresslist", selectListItems, new { #id = "valid-addresslist" })
Add the "-- Please select ..... below --"option as SelectListItem in the propertyList List.
Like: new SelectListItem { Text = "-- Please select ..... below --", Value = "none"}
Related
I have this code:
#Html.DropDownList("ddlTiposUsuarios", Model.tiposUsuarios.Select(item => new SelectListItem
{
Value = item.Id_Tipo_Usuario.ToString(),
Text = item.Nombre_Tipo_Usuario.ToString(),
Selected = "select" == item.Id_Tipo_Usuario.ToString()
}), new { #class = "form-select", aria_label = "Default select eaxmple" })
I retrieve a list of four elements from SQL Server and I want to set an option html element which "selected" attribute equals true, depending query from Controller. Any tips?
Instead of creating the SelectList on your View, create the list in your Controller and set it to a ViewBag and see how easy it becomes after that:
In your Controller, do this:
ViewBag.myddlItems = tiposUsuarios.Select(item => new SelectListItem
{
Value = item.Id_Tipo_Usuario.ToString(),
Text = item.Nombre_Tipo_Usuario.ToString()
});
and then in your View, you can construct your DropDownList using the ViewBag:
<select id="ddlTiposUsuarios" class="form-select" aria_label = "Default select eaxmple">
#foreach (SelectListItem option in ViewBag.myddlItems)
{
<option value="#option.Value" #(option.Value == "select" ? "selected='selected'" : "")>#option.Text</option>
}
</select>
I already got the default value and the value already became the default, but the default value has no highlight or focus in the dropdown list.
I am using SelectItemList function.
Controller:
private List<SelectListItem> SelectWeek() {
using(var db = new UsersContext()) {
int currentYear = DateTime.Now.Year;
selectListItems = db.WorkWeekDetails
.Where(item = >item.YEAR == currentYear).OrderBy(item = >item.WORKWEEK)
.Select(a = >new SelectListItem() {
Text = a.WORKWEEK,
Value = a.WORKWEEK
}).ToList();
selectListItems.Insert(0, new SelectListItem() {
Text = www, //www = "WW13"
Value = www, //www = "WW13"
Selected = true
});
}
return ViewBag.WorkWeek = selectListItems;
}
CSHTML:
#Html.DropDownList("WorkWeek", (List<SelectListItem>)ViewBag.WorkWeek, new { #class = "form-control", required = "required" })
I want "WW13" to be the default value and that value to be highlighted in the dropdown list.
//Example list of dropdownlist :
WW13 // This value will be the default.
ww01
ww02
ww03
ww04
ww05
ww06
ww07
ww08
ww09
ww10
ww11
ww12
ww13 // This value will be highlighted.
ww14
...
Dropdown list:
[
As #Aarif said you can use jquery to hightlight the selected option... something like this
Also I think you should probably pass your drop down list through a View model rather than a viewbag
window.onload = function() {
highlightSelected()
};
function highLightSelected(){
var model = #Html.Raw(Json.Encode(ViewBag.WorkWeek));
foreach(var item in model){
if(item.selected == true){
$("#mydropdownlist").val(item.value);
$("#mydropdownlist").addClass('active');
}
}
}
The syntax might not be exact but the idea is to check your list of SelectedListItem to find the one that is selected and set the drop list's value to that and also add the class which will highlight the selected value, but remember to remove this class on change of the dropdownlist value
I am rendering a select list in my view like so:
#Html.DropDownList("SelectCategory", (SelectList)ViewBag.Categories, "All")
I populate it like so:
ViewBag.Categories = new SelectList(db.Categories, "Id", "Name");
That renders:
<select id="SelectCategory" name="SelectCategory">
<option value="">All</option>
<option value="1">Fruit</option>
<option value="44">T-Shirts</option>
</select>
Issues:
1) The option value for All is empty, how can I put my value there, say 0 ?
2) How can I set a default selected value in #Html.DropDownList ?
The 3rd parameter of the DropDownList() method adds a 'label' option with a null value. Typically the option text is something like "Please select" and its purpose is to force a user to make a valid selection. If the label option is selected, a null value is submitted and ModelState is invalid (assuming the property your binding to is required).
If you want an additional option with <option value="0">All</option>, then you need to generate that in the SelectList you pas to the view, for example
List<SelectListItem> categories = db.Categories.Select(x => new SelectListItem()
{
Value = x.Id.ToString(), // assumes Id is not already typeof string
Text = x.Name
}).ToList();
categories.Insert(0, new SelectListItem(){ Value = "0", Text = "All" }) // Or .Add() to add as the last option
ViewBag.Categories = categories;
and in the view (note remove the 3rd parameter is you do not want the label option)
#Html.DropDownList("SelectCategory", (IEnumerable<SelectListItem>)ViewBag.Categories, "Please select")
In order to 'select' an option initially, you need to set the value of the property your binding to before you pass the model to the view, so if the value of property SelectCategory is "0", the the "All" option will be selected when the view is first displayed. If its "44", then the "T-Shirts" option will be selected. If the value of SelectCategory does not match one of the option values, or is null, then the first option will be selected (because soemthing has to be)
You could build your select "by hands"
<select>
#foreach (var item in optionList)
{
if(myCondition)
{
<option value="#item.Value" selected="selected">#item.Text</option>
}
else
{
<option value="#item.Value">#item.Text</option>
}
}
</select>
or using Linq in the view
var list = optionsList.Select(x => new SelectListItem { Text = x.Text, Value = x.Value, Selected = myCondition });
then you could used that list in one of the Html.DropdownList
Here is the full example
int catId = // Gets the catId to select somehow
IEnumerable<SelectListItem> options = optionsList
.Select(x => new SelectListItem {
Text = x.Text,
Value = x.Value,
Selected = x.Value == catId
}); // catId
And then you use it like this :
#Html.DropdownList("id-of-the-dropdown", options);
i m binding a dropdownlist in asp.net mvc 4 before binding i mark a value as selected but when the view is shown dropdown is binded but selected value is not selected
List<SelectListItem> citylist = new List<SelectListItem>();
var status = (DataSet)_rtmi_repo.GetCity(ref BaseObject);
foreach (DataRow v in status.Tables[0].Rows)
{
if (v["CODE"].ToString() == selectedval)
{
citylist.Add(new SelectListItem { Text = v["CODE"].ToString(), Value = v["CODE"].ToString(), Selected = true });
}
else
{
citylist.Add(new SelectListItem { Text = v["CODE"].ToString(), Value = v["CODE"].ToString() });
}
}
VIEW
#{var ddl = (IEnumerable<SelectListItem>)ViewBag.Location;}
#Html.DropDownListFor(model=>model.Location,ddl , new { #class = "form-control" })
even in ddl it show the selected true but after binding it always selects first value in list as selected
also created the filddle but here it works fine
"Example FIDDLE"
If you have a viewbag name same as the model property name, then the selected option will not be set to the DropDownListFor.
I am having a dropdownlist in my appliaction which I have binded through the database records
but on any of the edit form I want to set the selected index of the dropdown list how shall I do that ,I am Pastng my code here.
Code for binding the dropdownlist
public IList GetFeedbackList()
{
int feedbackId = 0;
string feedbackName = string.Empty;
using (var db = new brandconnectionsEntities())
{
return (IList )(from s in db.BC_FeedbackBy
select new
{
feedbackId =s.FeedbackById ,
feedbackName=s.FeedbackBy ,
})
.ToList ();
}
}
//Code for returning the list
IList allfeedbacks = _dropdownProvider.GetFeedbackList();
ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName");
//In the View Page
<%=Html.DropDownList("feedback_for", ViewData["feedback_for"] as SelectList, "--Select--", new { #class = "inputtext1" })%>
Please tell how shall I set the selected index from database
Thanks
Ritz
In the constructor for your select list you can specify the selected item....
ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName",
allfeedbacks.FirstOrDefault(f => f.FeedbackById == {ID of selected record}));
Pass a List of SelectListItems to the View. SelectListItem has a property selected.
IEnumerable<SelectListItem> itemList =
from item in Items
select new SelectListItem
{
Text = item.Name,
Value = item.Key,
Selected = ( item.Key == "TheKeyYouWantToSet")
};
ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName", selectedvalue);
At least in MVC2.
I had a problem which disappeared when I gave the dropdown the same name as the key. Ie:
<%=Html.DropDownList("feedbackId", ViewData["feedback_for"] as SelectList, "--Select--", new { #class = "inputtext1" })%>