This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I get this ASP.NET MVC SelectList to work?
What the hell is it? Is there some kind of a bug in DropDownList of MVC3?
SelectedValue doesn't show up as actually selected in the markup.
I am trying different approaches, nothing works.
public class SessionCategory
{
public int Id { get; set; }
public string Name { get; set; }
}
public static IEnumerable<SessionCategory> Categories
{
get
{
var _dal = new DataLayer();
return _dal.GetSesionCategories();
}
}
#{
var cats = Infrastructure.ViewModels.Session.Categories;
var sl = new SelectList(cats, "Id", "Name",2);
}
#Html.DropDownList("categories", sl);
Try the following:
Model:
public class MyViewModel
{
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
Controller:
public ActionResult Foo()
{
var cats = _dal.GetSesionCategories();
var model = new MyViewModel
{
// Preselect the category with id 2
CategoryId = 2,
// Ensure that cats has an item with id = 2
Categories = cats.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
})
};
}
View:
#Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "Value", "Text")
)
I think you need to make the selected value a string. There's also some value in using extension methods as detailed here.
Related
This question already has answers here:
MVC5 - How to set "selectedValue" in DropDownListFor Html helper
(5 answers)
Closed 4 years ago.
I am able to retrieve values from my database and display in the dropdownlist but I want to make it to have a selected value whereby my database has the ID value on it.
Here's my code:
AdminViewModel.cs
public IEnumerable<UserType> UserTypes { get; set; }
public int userTypeID { get; set; }
Controller
var userType = _context.UserTypes.ToList();
var viewModel = new AdminViewModel()
{
UserTypes = userType
};
return View(viewModel);
View
#Html.DropDownListFor(m => m.userTypeID, new SelectList(Model.UserTypes, "userTypeID", "userTypeName", Model.userTypeID), new { #class = "form-control" })
Selected value should be Caregiver based on the database value:
Use SelectListItem instead and set the value true for selected item.
AdminViewModel.cs:
public IEnumerable<SelectListItem> UserTypes { get; set; }
public int userTypeID { get; set; }
Controller:
var viewModel = new AdminViewModel();
SelectListItem item;
var userType = _context.UserTypes.ToList();
foreach(var uType in userType)
{
item = new SelectListItem();
item.Text = userType.userTypeName;
item.Value = userType.userTypeID;
if (item.Text == "Caregiver") // or any logic
{
item.Selected = true;
}
viewModel.UserTypes.Add(item);
}
return View(viewModel);
View:
#Html.DropDownListFor(m => m.userTypeID, Model.UserTypes , "Select", new { #class = "form-control" })
I have this MultipleSelectList in my view:
#Html.ListBoxFor(s => s.Id,
new MultiSelectList((IEnumerable<SelectListItem>)ViewData["ddlList"], "Value", "Text", Model.Id),
new { #style = "margin-top:250px", multiple = "multiple" })
This list is populated here
#{
using (var b = new Entity())
{
ViewData["ddlList"] = b.Table.Select(e => new SelectListItem()
{
Value = e.Id.ToString(),
Text = e.Name
}).ToList();
}
}
This is my model
public string Name { get; set; }
public int[] Id { get; set; }
The problem is that when I select multiple options, only the first one gets to my controller like this:
int[] value = modelObj.Id;
modelObj.Id;--stores my selected values
Someone knows how can I solve this?
Selected values will be array of string not array of int. So, change the type of Id property to type of string[]:
public string[] Id { get; set; }
Here is my Model
public class NewsViewModel
{
public NewsViewModel()
{
this.Categories = new List<Category>();
}
public int NewsId { get; set; }
[Required(ErrorMessage = "Please enter News Title")]
public string NewsTitle { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
I need to set Selected to be True if id exists in NewsViewModel.Categories collection
private IEnumerable<SelectListItem> GetCategories()
{
return db.Categories .Select(s=>new SelectListItem {
Value=s.Id.ToString(),
Text=s.Name,
Selected = model.Categories.Select(x => x.CategoryId).Contains(s.CategoryId);
}
And in View:
#Html.ListBoxFor(s => s.SelectedCategoriesIds, #Model.AllCategories, new { id = "DropDownList2", multiple = "multiple", #class = "form-control" })
See this question; you cannot use Contains with non-primitive types (like Category in this case). A different way to write your query that works around this limitation would be:
return db.Categories.Select(s=>new SelectListItem {
Value=s.Id.ToString(),
Text=s.Name,
Selected = model.Categories.Exists(z => z.CategoryId == s.CategoryId);
}
Instead of selecting the CategoryIds from model.Categories and then checking if s.CategoryId is in that list, we can check to see if there Exists() an item in model.Categories for which the CategoryId is the same as s.CategoryId.
Add the condition on the "selected" as a question mark condition.
var listSiteId = (from site in db.GetSiteId().ToList()
select new SelectListItem
{
Value = site.SITEID,
Text = site.NAME,
Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
}).ToList();
ViewBag.SiteId = listSiteId;
With the code below, i can select multiple radio buttons at the same time, that is a problem, a true radio button only works with ONE selected item. How do i re-arrange my code so that it acts like a real radio button and not like a checkbox like the code below?
for (int i = 0; i < Model.RadioButtonItems.Count; i++)
{
<div>
#Html.HiddenFor(m => m.RadioButtonItems[i].RBName)
#Html.LabelFor(l => l.RadioButtonItems[i].RBIsSelected, Model.RadioButtonItems[i].RBName)
#Html.RadioButtonFor(r => r.RadioButtonItems[i].RBIsSelected, true);
</div>
}
The rest of code:
Model:
public class ModelVariables
{
public List<Item> RadioButtonItems { get; set; }
}
public class Item
{
public string RBName { get; set; }
public bool RBIsSelected { get; set; }
}
public static class Repository
{
public static List<Item> RBFetchItems()
{
return new List<Item>()
{
new Item() {RBName = "Metal"},
new Item() {RBName = "Jazz"},
new Item() {RBName = "Trance"}
};
}
}
Controller:
var selectedRBItems = model.RadioButtonItems.Where(x => x.RBIsSelected).Select(x => x.RBName).ToList();
if (model.RadioButtonItems != null && selectedRBItems.Count > 0)
{
ViewBag.RBResults = "Successfully Logged Pressed RB's!";
}
else
{
ViewBag.RBResults = "You must select a radio button!";
}
Summary: this code let's you select multiple radiobuttons, i DONT want that, i want only one possible selection out of many options.
Each radio button has a different name attribute so they are not grouped. Your model needs a property to bind the selected value to, and a collection of items for the options
public class ModelVariables
{
[Required(ErrorMessage = "...")]
public string SelectedValue { get; set; }
public List<string> Options { get; set; }
}
and in the GET method
var model = new ModelVariables()
{
Options = new List<string>() { "Metal", "Jazz", "Trance" },
SelectedValue = ? // set this if you want one of the buttons initially selected
};
return View(model);
and in the view
foreach (var option in Model.Options)
{
<label>
#Html.RadionButtonFor(m => m.SelectedValue, option, new { id = "" })
<span>#option</span>
</label>
}
// add the following if you do not set an initial value in the GET method
#Html.ValidationMessageFor(m => m.SelectedValue)
I'm trying to do this:
This is my ViewModel and Model:
public class OpeningYearViewModel
{
public int OpeningYearId { get; set; }
public string Description { get; set; }
public List<Grade> GradesList { get; set; }
}
public class Grade
{
public int GradeId { get; set; }
public string Name { get; set; }
public int CurrencyId { get; set; }
public int Cost { get; set; }
}
This is my Controller. I build a SelecList here and pass it to the view through the ViewBag
OpeningYearViewModel viewmodel = new OpeningYearViewModel {
OpeningYearId = 1,
Description = "2015 - II",
GradesList = new List<Grade>
{
new Grade { GradeId = 1, Name = "Grade 1", CurrencyId = 1, Cost = 100 },
new Grade { GradeId = 2, Name = "Grade 2", CurrencyId = 2, Cost = 200 },
new Grade { GradeId = 3, Name = "Grade 3", CurrencyId = 2, Cost = 150 }
}
};
SelectList list = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "S/.", Value = "1"},
new SelectListItem { Text = "$", Value = "2"},
}, "Value" , "Text");
ViewBag.currencyList = list;
return View(viewmodel);
And in my View I need a DropDownListFor for every item on GradesList so I do this:
#model Test.Models.OpeningYearViewModel
#for(int i = 0; i < Model.GradesList.Count; i++)
{
#Html.DropDownListFor(x => x.GradesList[i].CurrencyId, new SelectList(ViewBag.currencyList, "Value", "Text"))
#Model.GradesList[i].CurrencyId //This is just to know the CurrencyId on every item.
}
I'm getting every select correctly rendered, but I can't get the correct option selected on the page load:
render of view
It is possible to do what I'm trying to do and I'm doing something wrong, or DropDownListFor works in a different way?
Thanks!
I can't understand why this is happening but you can workaround it by setting explicitly the selected value. This can be done by passing Model.GradesList[i].CurrencyId as fourth parameter to the SelectList's constructor:
#for(int i = 0; i < Model.GradesList.Count; i++)
{
#Html.DropDownListFor(x => x.GradesList[i].CurrencyId,
new SelectList(ViewBag.currencyList, "Value", "Text", Model.GradesList[i].CurrencyId))
}
Since, the DropDownListFor is used in loop to generate indexed inputs; so generate input controls will be generated with name as "GradeList[0].CurrencyId", "GradeList[1].CurrencyId"......Due to this framework will not bind the selected value in Select List as it is unable to get the value in reflection for selection. That's why you have to use the following SelectList constructor to set the selected value.
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue
)
However, if your DropDownListFor is bind to a simple expression like
#Html.DropDownListFor(model => model.CurrencyId, new SelectList(ViewBag.Items, "Value", "Text"))
then selection will work automatically.