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 working to create a view that contains a dropdownlist. To generate the select list items, I wrote a method to return the list of SelectListItem desired for this dropdown - one of which has an attribute of Selected set to true.
I have traced through the method generating the IEnumerable<SelectListItem> representative of the options I wish to render, and it is returning the desired result.
However when I use Html.DropDownList() utilizing the IEnumerable<SelectListItem> returned above, my rendered select element
has an initial blank option which does not appear in the DOM. Selecting any option will remove it, but I am confused as to why
the selected option from the List<SelectListItem> is not honored.
Static method generating list of SelectListItem:
public static IEnumerable<SelectListItem> GetDropDownValues()
{
IEnumerable<MyClass> myClassesForList = MyClass.GetItemsForList();
List<SelectListItem> retVal = new List<SelectListItem>();
retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });
IEnumerable<SelectListItem> myClassesSelectListItems =
from x in myClassesForList
select new SelectListItem
{
Text = x.Name,
Value = x.Value
};
return retVal.Concat(myClassesSelectListItems);
}
Pertinent Razor snippet:
#Html.DropDownList("dropDownVals", GetDropDownValues())
Edit 1: Screenshot of resulting drop-down list
Make sure there's not a viewbag/viewdata named dropDownVals, which holds a value that doesn't exist in the list returned by the method GetDropDownValues
What if you use AddRange instead of Concat:
retVal.Add(new SelectListItem() { Text = "Choose", Value = "0", Selected=true });
var myClassesSelectListItems = from x in myClassesForList
select new SelectListItem
{
Text = x.Name,
Value = x.Value
};
retVal.AddRange(myClassesSelectListItems);
return retVal;
I will try and explain my situation as best as I can with the information I have. The short of it is that based on the value in the text box, I need to hide options in a dropdown list.
I have a text box with a building limit. It has an ID and then a location number as there are multiple buildings on the same page:
<div class="col-md-6 col-sm-6">
<label>Limit</label>
#Html.TextBoxFor(m => m.Building.Limit, htmlAttributes: new { id = "buildingLimit-" + Model.LocationNum })
</div>
Below this I have a dropdown list with the a different ID but with the same location number:
<div class="col-md-6 col-sm-6">
<label>Occurrence</label>
#Html.DropDownListFor(m => m.Earthquake.Occurrence, new SelectList(Model.Earthquake.AggregateList, "Value", "Text"), htmlAttributes: new { id = "EarthquakeOcc-" + Model.LocationNum })
</div>
Right now, that dropdown list is not at all tied to the buildingLimit. It displays several different values which can be selected. What I would like to do is if the buildingLimit is say $250,000 then the dropdown list should not have values greater than that. If they change it again to $1,000,000 then the dropdown list needs to adjust to have values no greater than $1,000,000
I have really been struggling on this one now. It sounds simple enough but I can't figure out how to do this.
This is what I have so far:
$("[id^='buildingLimit-']").change(function () {
var location = $(this).attr("id").split("-")[1];
var buildingLimit = $(this).val();
var occArray = [];
$("[id^='EarthquakeOcc-']").each(function (i, selected) {
occArray[i] = $(selected).val();
alert(occAccary[i]);
if (occArray[i] > buildingLimit) {
$("[id^='EarthquakeOcc'] option[value = occArray[i]").remove();
}
});
I know that there are several things wrong with it: it only works when the text box is changed and it just removes. Does not add back through .append(). Also, the values are hard coded:
public List<SelectListItem> AggregateList
{
get
{
if (aggregateList == null)
{
aggregateList = new List<SelectListItem>();
aggregateList.Add(new SelectListItem { Text = "$100,000", Value = "100000" });
aggregateList.Add(new SelectListItem { Text = "$250,000", Value = "250000" });
aggregateList.Add(new SelectListItem { Text = "$500,000", Value = "500000" });
aggregateList.Add(new SelectListItem { Text = "$1,000,000", Value = "1000000" });
aggregateList.Add(new SelectListItem { Text = "$2,000,000", Value = "2000000" });
aggregateList.Add(new SelectListItem { Text = "$3,000,000", Value = "3000000" });
aggregateList.Add(new SelectListItem { Text = "$4,000,000", Value = "4000000" });
aggregateList.Add(new SelectListItem { Text = "$5,000,000", Value = "5000000" });
aggregateList.Add(new SelectListItem { Text = "$6,000,000", Value = "6000000" });
aggregateList.Add(new SelectListItem { Text = "$7,000,000", Value = "7000000" });
aggregateList.Add(new SelectListItem { Text = "$8,000,000", Value = "8000000" });
aggregateList.Add(new SelectListItem { Text = "$9,000,000", Value = "8000000" });
aggregateList.Add(new SelectListItem { Text = "$10,000,000", Value = "10000000" });
aggregateList.Add(new SelectListItem { Text = "$25,000,000", Value = "25000000" });
}
return aggregateList;
}
set { aggregateList = value; }
}
First things first, you're going to need an immutable list of all possible values. Trying to remove and recreate options, while also keeping everything ordered properly and such is an unnecessary pain. If you have a list of possible values, you can simply pull from that list, up to the defined threshold, based on the text box entry, to recreate the entire list of options. I would also recommend using a nice little JS library called accounting.js. It's not a strict requirement to make this work, but it makes converting back and forth between formatted currency string values and actual numeric values a ton easier.
Basically, you just need a list of the values in JS:
var MyNamespace = MyNamespace || {};
MyNamespace.AggregateList = [
100000,
250000,
500000,
...
];
If you would prefer to create this list in your MVC view model and pass it to the view you can use something like the following instead:
MyNamespace.AggregateList = #Json.Encode(Model.AggregateListValues);
Where AggregateListValues would be a List<int>, or similar.
Next, the way you're selecting the building limit and earthquake occurrence fields is highly inefficient. It's better to put each pair of fields inside a wrapper such that you can select the other based on its proximity:
<div class="location">
<input id="buildingLimit" />
<select id="EarthquakeOcc"> ... </select>
</div>
That code is intentionally simplified to illustrate what's happening; you're still free to use whatever other HTML you currently have wrapping those fields. Just make sure that both are grouped together within one parent. Then:
$('[id^=buildingLimit]').on('change', function () {
var parent = $(this).closest('.location');
var select = $('[id^=EarthquakeOcc]', parent);
});
Also, for what it's worth, this frees you up to use the original ids, without having to manually specify the id, or and probably better, you could add a class to the fields instead, such that you can select them based on that class rather than their id attributes starting with a certain string, which would be a much cheaper selector for jQuery to process. (When you select by attribute, your selector is actually *[attribute=value]. In other words, jQuery must select every element in the DOM and then filter out the ones that don't have matching id values. Using a selector like input[attribute=value] would be better, as that narrows the field down to just input elements before jQuery much search each one. However, classes will always be faster, as jQuery can just rely on the native document.getElementsByClassName.)
For your event handler:
$('[id^=buildingLimit]').on('change', function () {
var parent = $(this).closest('.location');
var select = $('[id^=EarthquakeOcc]', parent);
// if you choose not to use accounting.js, you just need to ensure that the value
// gets turned into a number, using a combination of something like `replace` with
// a regex and `parseInt`, etc.
var limit = accounting.unformat($(this).val());
var output = [];
var i = 0;
while (MyNamespace.AggregateList[i] <= limit) {
// If you choose not to use accounting.js, you just need to implement your
// own logic for formatting the number as you want
output.push('<option value="' + MyNamespace.AggregateList[i] + '">$' + accounting.formatNumber(MyNamespace.AggregateList[i]) + '</option>');
i++;
}
select.html(output.join(''));
});
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" })%>