I have the following DropDownList on a View Layout page that displays languages from an SQL database. I want the selected item of the dropdownlist to be the page current culture (originalCulture). How can I accomplish that?
For example if the page current culture (originalCulture="en") is equal to (item.language_UI="en") then the DDL selected item should be English (item.language). I know that it's easy but I'm not familiar with Razor codes. Can someone help?
#{
var db = Database.Open("DefaultConnection");
var listLanguage = "SELECT language, language_UI FROM Languages";
var originalCulture = Convert.ToString(System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName);
List<SelectListItem> languagedropdownlistdata = new List<SelectListItem>();
bool isSelected = false;
foreach (var item in db.Query(listLanguage))
{
languagedropdownlistdata.Add(new SelectListItem
{
Text = item.language,
Value = item.language_UI,
Selected = isSelected
});
}
}
And here is the DropDownList on the content page:
#Html.DropDownList("lang", languagedropdownlistdata
<input type="submit" value="Select" />
It is not really the "Razor" codes. It is mostly C# :)
Your isSelected variable seems to be false always.
You need to change your loop body to the following:
foreach (var item in db.Query(listLanguage))
{
languagedropdownlistdata.Add(new SelectListItem
{
Text = item.language,
Value = item.language_UI,
Selected = (item.language_UI == originalCulture)
});
}
The statement (item.language_UI == originalCulture) would be true only if the language_UI propery will contain exactly the same string as originalCulture, therefore your code should work properly.
Related
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
Here I have dropdownlist which contains multiple values. and user can select any no of values by clicking the checkbox infront of the value as shown below.
Following is my c# code.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"), new { id = "det" , multiple= "multiple"})
$(document).ready(function() {
$('#det').multiselect();
});
When user click save button I want to get the user selected list. I am using following code to get the values.
$("#det").val()
But the above value is empty. How to get the existing selected value?
And also I want to show the values as selected based on server side values.
I am creating model and set model property with hardcoded values as below.
model.Detail = "Cheese, Tomatoes";
But these values are not getting selected in dropdownlist as well.
Used plugin here - link
Any help?
Thanks.
You need to add multiple= "multiple" in the attributes for multiselect to work.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"),
new { id = "det", multiple= "multiple" });
to set the values:
<script>
var selectedValues = #model.Detail;
var dataarray = selectedValues.split(",");
// Set the value
$("#det").val(dataarray);
$("#det").multiselect("refresh");
</script>
First of all, use #Html.ListBoxFor that works best with Multiselect js.
In order to get the values for selected options, I have created the following client side code which returns list of value in form of String arrays
function GetDropDownVal() {
var selectidList = [];
var selectedItem = $("#ListQueCatId").val();
// .multiselect("getChecked") can also be used.
if (selectedItem != null) {
for (var i = 0; i < selectedItem.length; i++) {
selectidList.push(selectedItem[i]);
}
}
return selectidList;
}
This is how I have implemented the code
View Side Code
#Html.ListBoxFor(m => m.ListQueCatId, (SelectList)ViewBag.AllQueCat as MultiSelectList, new { #class = "form-control listQueCatIdDdl" })
Javascript Code
$(".listQueCatIdDdl").multiselect({ noneSelectedText: "--Select Category(s)--" });
Also, make sure to bind a model property of Type List in my case, ListQueCatId is List< Guid>, hence while you post the form, you will get the selected values in your model.
Also, I don't think there is need to add multiple attribute as the plugin is meant for selecting multiple values.
I would like to send the selected dropdown option into model.Feit
Assuming, i need DropDownListFor, then select table, then the dropdown..?
//here's my drop down menu in my controller
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Owner", Value = "0", Selected = true });
items.Add(new SelectListItem { Text = "Leader", Value = "1" });
ViewBag.items = items;
//this works fine, but the selected option has to be inserted into my database when submitted
//the first line shows the label
<div class="editor-label">#Html.LabelFor(model => model.Feit)</div>
//the second line needs to show as a dropdownlist with the 2 options above here
<div class="editor-field">#Html.DropDownListFor(model => model.Feit, "items")</div>
//when the option is selected, and submit is pressed this has to be sent to the db
// this works for all other fields, but my syntax is wrong at , "items"
Since you've already populated an IEnumerable<SelectListItem> in your viewbag, you just need to access it and cast it to ensure the correct DropDownListFor overload is used:
#Html.DropDownListFor(model => model.Feit, (IEnumerable<SelectListItem>)ViewBag.items)
model.Feit should be of type int or something that can hold the value of the selected item.
Use this
#Html.DropDownListFor(m => m.Feit, new SelectList(ViewBag.items, "Id","Name"),"Select")
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 have a Search Edit view which is strongly typed to my Search model class seen below (simplified).
I want to display the custodians that are attributed to the Search being edited in a listbox showing all Custodians, with the current ones selected.
My controller's Get Edit action is thus:
public ActionResult Edit(int id, int searchListId = 0)
{
if (searchListId != 0)
{
Session["CurrentSearchListID"] = searchListId;
}
ProjectContext mydb = db;
Search search = Search.Find(mydb, id);
IEnumerable<SelectListItem> selectedItems =
from c in Custodian.List(mydb)
select new SelectListItem
{
Selected = (search.Custodians.Contains(c)),
Text = c.CustodianName,
Value = c.ToString()
};
ViewBag.Custodians = selectedItems;
return View(search);
}
And my Views listbox is thus:
#{
//List<Kiersted.Keps.BusinessObjects.Custodian> Custodians = ViewBag.Custodians;
IEnumerable<SelectListItem> SelectedItems = ViewBag.Custodians;
}
#Html.ListBox("Custodians", SelectedItems);
This produces a listbox with the Custodians depicted, but none are selected (I have confirmed that several of the SelectListItems accurately describe the custodian as selected. I have tried using ListBoxFor and it produces the same thing when populated with a MultiSelectList.
Finally I decided to just force it to do what I want, but this does not return selected Custodians on Submit.
<select id="Custodians" multiple="multiple" name="Custodians">
#foreach (Kiersted.Keps.BusinessObjects.Custodian cust in Custodians)
{
if (Model.Custodians.Contains(cust))
{
<option value="#cust.CustodianID" selected="selected">#cust.CustodianName</option>
}
else
{
<option value="#cust.CustodianID" >#cust.CustodianName</option>
}
}
</select>
Anyone know how you are supposed to do this?
Edits:
ListBoxFor example
OK so after fiddling around with it for a while longer, I have now gotten Custodians selected in the listbox that correspond to the Search Custodians. Below is the view code:
<div class="editor-field">
#Html.ListBoxFor(model => model.Custodians, allCustodians.Select(cust => new SelectListItem {
Text = cust.CustodianName,
Value = cust.CustodianID.ToString(),
Selected = true}),
new { Multiple = "multiple" })
</div>
If I select several more custodians, how do I get them (or their corresponding values rather) back to the control upon submit?
Seeing that after your edit the problem boils down to multiple select model binding, perhaps you will find these useful?
How does a multiple select list work with model binding in ASP.NET MVC?
http://ittecture.wordpress.com/2009/04/30/tip-of-the-day-198-asp-net-mvc-listbox-controls/