#Html.DropDownList(expression: model => model.CategoryID,
new List<SelectListItem>(Model.CategorySelectListItem, dataValueField: "Value",
dataTextField: "Text"),htmlAttributes:new {#class = "form-control"})
This is my code, what does the error mean and how do I fix it?
What you need is a new instance of SelectList actually not a List of SelectListItem, change your code like this and it works fine:
#Html.DropDownList(expression: model => model.CategoryID,
new SelectList(Model.CategorySelectListItem, dataValueField: "Value",
dataTextField: "Text"),htmlAttributes:new {#class = "form-control"})
Related
I'm trying to get this datepicker field to populate with today's date but it's not happening for some reason. I can't find a reference for what options are accepted in the "new {}" section.
#Html.LabelFor(d => d.ServiceOn, new { #class = "control-label" })
#Html.EditorFor(d => d.ServiceOn, "DatePicker", new { disableMinDate = true, Value = DateTime.Today })
#Html.ValidationMessageFor(d => d.ServiceOn, "", new { #class = "text-danger" })
I've tried value, Value and #Value but the resulting html always shows value="". I'm wondering if maybe the datepicker itself is zeroing out the field. I feel like I'm missing something obvious here.
This should work:
#Html.LabelFor(d => d.ServiceOn, new { #class = "control-label" })
#{Model.ServiceOn= DateTime.Today;}
#Html.EditorFor(d => d.ServiceOn, "DatePicker", new { disableMinDate = true })
#Html.ValidationMessageFor(d => d.ServiceOn, "", new { #class = "text-danger" })
HTML work with the ModelState, not from the model itself.
If you want more loose helpers, ise #Html.Editor instead.
In my MVC application, I am retrieving a list of objects based on an ID and stuffing those objects into a Listbox via a SelectList. Here is what I have:
C#
ViewBag.SpecCatListBox = new SelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text");
HTML/Razor
#Html.ListBoxFor(model => model.LstSpecialCategories, (SelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", #class = "form-control" })
On page load, the listbox is filled with the correct options, except that they're not selected. Is there a way to do this without looping (which is what I've seen in other posts)?
Any help is appreciated.
UPDATE
I've edited a few things, along with added a line of code.
C#
ViewBag.SpecCatListBox = new SelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text", SelectListMethods.LstChosenSpecCat(incidentVm.ID));
ViewBag.SpecCatIds = db.TBL_AssocIncidentSpecialCat.Where(x => x.IncidentId == incidentVm.ID)
.Select(x => x.SpecialCategoriesId).ToList();
HTML/Razor
#Html.ListBoxFor(model => model.LstSpecialCategories, new MultiSelectList(ViewBag.SpecCatListBox, "Value", "Text", ViewBag.SpecCatIds), new { id = "SpecialCat-ListBox", #class = "form-control" })
This is selecting all of the options as needed, but is there a way to not use 2 Viewbag objects?
I have figured this out.
C#
ViewBag.SpecCatListBox = new MultiSelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text", SelectListMethods.LstChosenSpecCat(incidentVm.ID).Select(x => x.Value));
HTML/Razor
#Html.ListBoxFor(model => model.LstSpecialCategories, (MultiSelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", #class = "form-control" })
As the question says:
How to set selectedValue in DropDownListFor Html helper?
Tried most of the other solutions but none worked that's why I am opening a new question.
Nothing of these helped:
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2), htmlAttributes: new { #class = "form-control" })
//Not working with or without cast
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Single(x => x.Id == 2)), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Where(x => x.Id == 2).FirstOrDefault()), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", new SelectListItem() { Value="2", Selected=true}), htmlAttributes: new { #class = "form-control" })
I would like to avoid manual creation of SelectListItems or a ViewModel just for the list if possible.
When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option.
Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using
#Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))
Note your can inspect the source code, in particular the SelectInternal() and GetSelectListWithDefaultValue() methods to see how it works in detail.
To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view
I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita and that you generate the SelectList in the controller
var model = new YourModel()
{
TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
TipPopustaId = 2 // set the selected option
}
return View(model);
so the view becomes
#Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { #class = "form-control" })
Make Sure that your return Selection Value is a String and not and int when you declare it in your model.
Example:
public class MyModel
{
public string TipPopustaId { get; set; }
}
public static class EnumHelper
{
public static SelectList EnumToSelectList<TEnum>(this Type enumType, object selectedValue)
{
return new SelectList(Enum.GetValues(enumType).Cast<TEnum>().ToList().ToDictionary(n=> n), "Key", "Value", selectedValue);
}
}
And in your View:
#Html.DropDownListFor(model => model.Role, EnumHelper.EnumToSelectList<Role>(typeof(Role), Model.Role), new { htmlAttributes = new { #class = "padding_right" } })
#Html.ValidationMessageFor(model => model.Role, "", new { #class = "text-danger" })
Instead of EnumToList use any Other List and select Key and Value of your Listtype Properties
I noticed there is no razor oriented approach, i added below
var prices = from P in Model[idx].prices.Values
where !P.Key.ToLower().Contains("san")
select new SelectListItem()
{
Text = P.Key + " Month " + (Convert.ToDecimal(P.Value) + ((Convert.ToDecimal(P.Value) / 100) * 20)).ToString("0.##") + " $",
Value = P.Key
};
prices.ToList()[0].Selected = true;
#Html.DropDownListFor(model => prices.ToList()[0], prices)
Just going to add my preferred way of doing this is to render the select statement myself as it gives greater control over the HTML, rather than using the Razor control.
<select class="form-control" id="my-id">
#foreach (var item in Model.ListOfItems) {
var selected = "";
if (item.Value == "whatever") {
selected = "selected='selected'";
}
<option #selected value="#item.Value">#item.Text</option>
}
</select>
As the question says:
How to set selectedValue in DropDownListFor Html helper?
Tried most of the other solutions but none worked that's why I am opening a new question.
Nothing of these helped:
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2), htmlAttributes: new { #class = "form-control" })
//Not working with or without cast
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Single(x => x.Id == 2)), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Where(x => x.Id == 2).FirstOrDefault()), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", new SelectListItem() { Value="2", Selected=true}), htmlAttributes: new { #class = "form-control" })
I would like to avoid manual creation of SelectListItems or a ViewModel just for the list if possible.
When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option.
Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using
#Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))
Note your can inspect the source code, in particular the SelectInternal() and GetSelectListWithDefaultValue() methods to see how it works in detail.
To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view
I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita and that you generate the SelectList in the controller
var model = new YourModel()
{
TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
TipPopustaId = 2 // set the selected option
}
return View(model);
so the view becomes
#Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { #class = "form-control" })
Make Sure that your return Selection Value is a String and not and int when you declare it in your model.
Example:
public class MyModel
{
public string TipPopustaId { get; set; }
}
public static class EnumHelper
{
public static SelectList EnumToSelectList<TEnum>(this Type enumType, object selectedValue)
{
return new SelectList(Enum.GetValues(enumType).Cast<TEnum>().ToList().ToDictionary(n=> n), "Key", "Value", selectedValue);
}
}
And in your View:
#Html.DropDownListFor(model => model.Role, EnumHelper.EnumToSelectList<Role>(typeof(Role), Model.Role), new { htmlAttributes = new { #class = "padding_right" } })
#Html.ValidationMessageFor(model => model.Role, "", new { #class = "text-danger" })
Instead of EnumToList use any Other List and select Key and Value of your Listtype Properties
I noticed there is no razor oriented approach, i added below
var prices = from P in Model[idx].prices.Values
where !P.Key.ToLower().Contains("san")
select new SelectListItem()
{
Text = P.Key + " Month " + (Convert.ToDecimal(P.Value) + ((Convert.ToDecimal(P.Value) / 100) * 20)).ToString("0.##") + " $",
Value = P.Key
};
prices.ToList()[0].Selected = true;
#Html.DropDownListFor(model => prices.ToList()[0], prices)
Just going to add my preferred way of doing this is to render the select statement myself as it gives greater control over the HTML, rather than using the Razor control.
<select class="form-control" id="my-id">
#foreach (var item in Model.ListOfItems) {
var selected = "";
if (item.Value == "whatever") {
selected = "selected='selected'";
}
<option #selected value="#item.Value">#item.Text</option>
}
</select>
I have this:
#Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"))
And would like it to be rendered as this:
<select required>
<option>...</option>
...
How would I do this?
Use this:
#Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"), new {required = "required"})
It won't achieve the shorthand <select required but it should have the same effect. Although I've found you could achieve that exact element using
#Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"), new {required = (string)null})
Which is a little ugly.
VB.NET
#Html.DropDownListFor(Function(Model) Model.ProgramTypeId, New SelectList(Model.allPrograms,
"ProgramTypeId", "ProgramName"), "Select Program....",
New With {Key .class = "form-control", Key .required = "Required"})
Try the following
#Html.DropDownList("PlanType", null, "Select Plan Type", htmlAttributes: new { #class = "form-control", required = "Select Plan Type" })