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")
Related
The example that I'm looking at is https://www.aspsnippets.com/Articles/Cascading-Dependent-DropDownList-in-ASPNet-MVC.aspx
The example works well. But cannot see how to specify a selected value before passing the model to the view.
You can specify the "Selected" value by
model.Countries.Add(new SelectListItem { Text = country.CountryName, Value = country.CountryId.ToString(), Selected = true });
The Viewmodel results shows the specified item with the Selected = true.
But the dropdown in the view #Html.DropDownListFor(m => m.CountryId, Model.Countries, "Please select", new { onchange = "document.forms[0].submit();" }) just ignores it.
Can anyone see a work around to get the selected value to be displayed?
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 have an html dropdownlistfor which is being populated from my database, this I was able to do successfully but the issue I am having now is including an additional option not available in the database as an option that can also be selected.it is actually a list of items but I want a give an option ALL which when selected means the user is selecting all the items displayed in the database, my major issue is how to include the ALL option. I have searched and read similar questions but they are not what am trying to achieve. thanks for your help. here is my code
in my controller I have this:
var load = from bh in db.IV_001_ITEM
select bh;
ViewBag.selection = new SelectList(load.ToList(), "item_code", "item_name", glay.vwstring2);
in my view I have this:
<div class="col-sm-2">
#Html.DropDownListFor(m => m.vwstring2, ViewBag.selection as SelectList, "Select", new { #class = "form-control", required = "required", id = "selectc" } )
</div>
You can use the Add method to explicitly add an extra option (SelectListItem)
List<SelectListItem> optionList = db.IV_001_ITEM
.Select(x=>new SelectListItem { Value=x.item.code,
Text=x.itemName}).ToList();
// Now add the item you want
optionList.Add(new SelectListItem { Value="Foo",Text="Bar"});
//use this now
ViewBag.Items = optionList;
// You can set the selected item on your view model property
myViewModelObject.vwstring2 = glay.vwstring2; //For the selected item
return View(myViewModelObject);
In your view,
#Html.DropDownListFor(m => m.vwstring2, ViewBag.Items as List<SelectListItem>,
"Select", new { #class = "form-control"})
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 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;