I want to assign some ID attribute name to my Dropdown list which is using data from the ViewBag as,
ViewBag.Group = new SelectList(group, "GroupId", "Name");
and in the View side I have used Razor syntax for showing the Dropdown as,
#Html.DropDownList("Group", "New", new { id="testID" } )
But I am getting the error on this line. Can I just assign ID of This Razor syntax?
I know that the ID is generated with the Name "Playlist" But I am having 2 different dropdowns using same ViewBag. Because of that I have to assign different "ID" attribute value for them. How can it be done?
You should be using something like this
#Html.DropDownList("Group",null,new{#id="testID"});
because the data for the DropDownList comes from the ViewBag to name Group
Try it:
In controller
ViewBag.EmployeeId = new SelectList(db.tb_employees, "id", "last_name");
In View
#Html.DropDownList("EmployeeId", (IEnumerable<SelectListItem>)ViewBag.EmployeeId,"Show All", new { #class = "form-control" })
Related
I have a view that has a form to create a new database entry using entityframework.
I can get the dropdown selection to assign the productId value but I also need it to assign a second value which i cannot seem to get.
#Html.DropDownListFor(model => model.SerialNumber.ProductId ,
new SelectList(Model.Products, "Id", "Name") , "Select Product",
new { #class = "form-control", id = "productDropDownList" } )
How can i get this dropdown selection to fill both productId and name from one single selection?
I have a DDL in my view and i read items and values of this DDL from DB like this :
ViewBag.ContentGroup = new SelectList(obj.GetContentGrouplist(), "Id", "Name");
I put it in viewbag and i read the viewbag from the view like this :
<div class="editor-label">
#Html.LabelFor(model => model.ContentGroupFKId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ContentGroupFKId, (SelectList)ViewBag.ContentGroup)
#Html.ValidationMessageFor(model => model.ContentGroupFKId)
</div>
So i need a DDL that the first item of that be null how can i do that?
I tried this but it doesn't work:
#Html.DropDownListFor(x => x.ContentGroupFKId,new SelectList(new List<Object> {new {value = null, text = "Select"} (SelectList)ViewBag.ContentGroup)
Best regards.
I don't think you can. Whatever value you provide is going to be used to generate html in the form of a select list, which doesn't support null. As long as you have a DropDownListFor, it is going to set a value, even if it is empty. The best thing you can do is make the first value a "Please select an item" option and set it to null server side.
There isn't a great way to add the "Please Select" option (at least none that I have seen. People are welcome to correct me though!), but there are a few ways to do it. One would be to create a dummy content group that just has a name and id.
var contentGroups = obj.GetContentGrouplist();
contentGroups.Insert(0, new ContentGroup{Id = "0", Name = "Please select a content group"};
ViewBag.ContentGroup = new SelectList(contentGroups, "Id", "Name");
Or you can create an object (which you would use anywhere you needed this functionality) that just holds a text and value property and then manually add all of your content groups to it, including the empty one.
class DropDownListOption{
public string Text{get;set;}
public string Value{get;set;}
}
then in your code
var contentGroups = obj.GetContentGrouplist();
var options = new List<DropDownListOption>();
options.Add(new DropDownListOption{ Id = "0", Text = "Please select a content group"};
foreach(var group in contentGroups)
{
options.Add(new DropDownListOption{ Id = group.Id, Text = group.Name};
}
ViewBag.ContentGroup = new SelectList(options, "Id", "Name");
Both of these options will work. I like the second option better because you can create a generic method of handling all drop down lists a certain way. You will have to handle ContentGroups with an ID of 0 as being null when the user submits the form, but at least it is a way of tracking it.
If I think of another way ill add it.
I've the following code for a DropDownListFor and is working ok
#Html.DropDownListFor(Function(model) model.Habilitacoes, New SelectList(ViewBag.Habilitacoes, "KeyHL", "DescricaoHL"), New With {.class = "FillHSpace"})
The ViewBag.Habilitacoes is a List(Of T)
But know I want to add the SelectedValue to the DropDownListFor, so I've used the following code but doesn't work.
#Html.DropDownListFor(Function(model) model.Habilitacoes, New SelectList(ViewBag.Habilitacoes, "KeyHL", "DescricaoHL", model.Habilitacoes), New With {.class = "FillHSpace"})
How can I declare the SelectedValue?
You should not use the same property as first and second argument of the DropDownListFor helper. The first argument is a scalar property and the second a collection:
#Html.DropDownListFor(Function(model) model.SelectedHabilitacoes, New SelectList(ViewBag.Habilitacoes, "KeyHL", "DescricaoHL"), New With {.class = "FillHSpace"})
and then in your controller:
model.SelectedHabilitacoes = "123"
DropdownListFor has overloads to accomplish this
DropDownListFor([SelectedValue], [SelectList], optional HTML Attributes)
Normally you would go
DropDownListFor(model => model.ID, (SelectList)ViewsBag.MySelectList, optional HTML Attributes)
The selected value will be automatically bound to the dropdown list, and will automatically be posted the the model.ID value
if this doesn't help id ask you to post your model.
I'm building my first MVC application after years of doing webforms, and for some reason I am not able to make this work:
#Html.DropDownList("PriorityID", String.Empty, new {#class="textbox"} )
Error message:
System.Web.Mvc.HtmlHelper<SPDR.Models.Bug>' does not contain a definition for DropDownList and the best extension method overload System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, object) has some invalid arguments
Any help greatly appreciated!
Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.
My view was one of the auto-generated ones, and contained this line of code:
#Html.DropDownList("PriorityID", string.Empty)
To add html attributes, I needed to do something like this:
#Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { #class="dropdown" })
Thanks again to #Laurent for your help, I realise the question wasn't as clear as it could have been...
UPDATE:
A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute
#Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { #class = "dropdown" })
As the signature from the error message implies, the second argument must be an IEnumerable, more specifically, an IEnumerable of SelectListItem. It is the list of choices. You can use the SelectList type, which is a IEnumerable of SelectListItem.
For a list with no choices:
#Html.DropDownList("PriorityID", new List<SelectListItem>(), new {#class="textbox"} )
For a list with a few choices:
#Html.DropDownList(
"PriorityID",
new List<SelectListItem>
{
new SelectListItem { Text = "High", Value = 1 },
new SelectListItem { Text = "Low", Value = 0 },
},
new {#class="textbox"})
Maybe this tutorial can be of help: How to create a DropDownList with ASP.NET MVC
If you are add more than argument ya dropdownlist in Asp.Net MVC.
When you Edit record or pass value in view bag.
Use this it will be work:-
#Html.DropDownList("CurrencyID",null,String.Empty, new { #class = "form-control-mandatory" })
There are some options in constructors look,
if you don't have dropdownList and you wanna insert CSS class you can use like
#Html.DropDownList("Country", null, "Choose-Category", new {#class="form-control"})
in this case Country is the name of your dropdown, null is for you aren't passing any generic list from your controller "Choose-Category" is selected item and last one in CSS class
if you don't wanna select any default option so simple replace "Choose-Category" with ""
You Can do it using jQuery
$("select").addClass("form-control")
here, Select is- html tag,
Form-control is- class name
#Html.DropDownList("SupplierId", "Select Supplier")
and here, SupplierId is ViewBagList,
Select Supplier is - Display Name
Simply Try this
#Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { #class="dropdown" })
But if you want a default value or no option value then you must have to try this one, because String.Empty will select that no value for you which will work as a -select- as default option
#Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, String.Empty, new { #class="dropdown" })
Try below code:
#Html.DropDownList("ProductTypeID",null,"",new { #class = "form-control"})
Try this:
#Html.DropDownList(
"country",
new[] {
new SelectListItem() { Value = "IN", Text = "India" },
new SelectListItem() { Value = "US", Text = "United States" }
},
"Country",
new { #class = "form-control",#selected = Model.Country}
)
You can simply do this:
#Html.DropDownList("PriorityID", null, new { #class="form-control"})
Try This
#Html.DropDownList("Id", null, new { #class = "ct-js-select ct-select-lg" })
I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar question on Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.
<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>
I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.
After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor. The reason is you are using ViewBag's name the same as the model's property.
Example
public class employee_insignia
{
public int id{get;set;}
public string name{get;set;}
public int insignia{get;set;}//This property will store insignia id
}
// If your ViewBag's name same as your property name
ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
#Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")
The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.
Example
ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
#Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")
If you're doing it properly and using a model--unlike all these ViewBag weirdos--and still seeing the issue, it's because #Html.DropDownListFor(m => m.MyValue, #Model.MyOptions) can't match MyValue with the choices it has in MyOptions. The two potential reasons for that are:
MyValue is null. You haven't set it in your ViewModel. Making one of MyOptions have a Selected=true won't solve this.
More subtly, the type of MyValue is different than the types in MyOptions. So like, if MyValue is (int) 1, but your MyOptions are a list of padded strings {"01", "02", "03", ...}, it's obviously not going to select anything.
Try:
<%= Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")%>
or in Razor syntax:
#Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")
The expression based helpers don't seem to respect the Selected property of the SelectListItems in your SelectList.
While not addressing this question - it may help future googlers if they followed my thought path:
I wanted a multiple select and this attribute hack on DropDownListFor wasn't auto selecting
Html.DropDownListFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems, new {multiple= "multiple" })
instead I should have been using ListBoxFor which made everything work
Html.ListBoxFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems)
I also having similar issue and I solve it by as follows,
set the
model.States property on your controller to what you need to be selected
model.States="California"
and then you will get "California" as default value.
I encountered this issue recently. It drove me mad for about an hour.
In my case, I wasn't using a ViewBag variable with the same name as the model property.
After tracing source control changes, the issue turned out to be that my action had an argument with the same name as the model property:
public ActionResult SomeAction(string someName)
{
var model = new SomeModel();
model.SomeNames = GetSomeList();
//Notice how the model property name matches the action name
model.someName = someName;
}
In the view:
#Html.DropDownListFor(model => model.someName, Model.SomeNames)
I simply changed the action's argument to some other name and it started working again:
public ActionResult SomeAction(string someOtherName)
{
//....
}
I suppose one could also change the model's property name but in my case, the argument name is meaningless so...
Hopefully this answer saves someone else the trouble.
I know this is an old question but I have been having the same issue in 2020.
It turns out the issue was with the model property being called "Title", I renamed it to "GivenTitle" and it now works as expected.
From
Html.DropDownListFor(m => m.Title, Model.Titles, "Please Select", new { #class = "form-control" })
to
Html.DropDownListFor(m => m.GivenTitle, Model.GivenTitles, "Please Select", new { #class = "form-control" })
this problem is common. change viewbag property name to other then model variable name used on page.
One other thing to check if it's not all your own code, is to make sure there's not a javascript function changing the value on page load. After hours of banging my head against a wall reading through all these solutions, I discovered this is what was happening with me.
The issue at least for me was tied to the IEnumerable<T>.
Basically what happened was that the view and the model did not have the same reference for the same property.
If you do this
IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}
Then bind this using the
#Html.DropDownListFor(model => model.Id, Model.CoolNames)
The View loses track of the CoolNames property,
a simple fix is just to add .ToList() After dooing a projection (.Select()) ;).
I had the same problem. In the example below The variable ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] has a SelectListItem list with a default selected value but such attribute is not reflected visually.
// data
var p_estadoAcreditacion = "NO";
var estadoAcreditacion = new List<SelectListItem>();
estadoAcreditacion.Add(new SelectListItem { Text = "(SELECCIONE)" , Value = " " });
estadoAcreditacion.Add(new SelectListItem { Text = "SI" , Value = "SI" });
estadoAcreditacion.Add(new SelectListItem { Text = "NO" , Value = "NO" });
if (!string.IsNullOrEmpty(p_estadoAcreditacion))
{
estadoAcreditacion.First(x => x.Value == p_estadoAcreditacion.Trim()).Selected = true;
}
ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] = estadoAcreditacion;
I solved it by making the first argument of DropdownList, different to the id attribute.
// error:
#Html.DropDownList("SELECT__ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...
// solved :
#Html.DropDownList("DROPDOWNLIST_ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...