I have the following declaration in Razor:
#Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>, ViewBag.CurrentUserRole as string, new { #class = "form-control" }), and it results in a drop-down that looks as follows on page load:
And when I click on the dropdown arrow, I see:
So basically, the User Role is duplicated. How can I change this so that instead of making a new duplicate element, it defaults to the element it is supposed to be? Basically, since ViewBag.RolesEdit is a list, and ViewBag.CurrentUserRole is guaranteed to have an element that is equal to exactly one item in the afformentioned list, how can I loop through the list to compare each other and set the default?
Thank You.
When using Html.DropDownList helper method, To set one option to be pre selected, you just need to set the value of that option to the the ViewBag dictionary with the same key used to generate the SELECT element.
#Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>)
Assuming your action method is setting ViewBag.SelectedRole to the value of the option you want to select.
ViewBag.RolesEdit= new List<SelectListItem>{
new SelectListItem { Value="Administrator", Text="Administrator"},
new SelectListItem { Value="Employees", Text="Employees"},
new SelectListItem { Value="RegularUser", Text="Regular User"},
}
ViewBag.SelectedRole ="RegularUser";
return View();
If you prefer to use Html.DropDownListFor helper method with a strongly typed view and view model, you can follow this post
What is the best ways to bind #Html.DropDownListFor in ASP.NET MVC5?
Related
Been googling for a while, but I can't seem to get any closer.
I'm using MVC with an EF Database structure.
I want the dropdownlist items in the View to show up with different names than what they come up with.
Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name. Eventually, the selected field needs to be used in another lambda as the Byte that it was.
Edit
//view
<p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
#Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })
....
//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
orderby t.TYPE
select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);
....
Thanks in advance.
You can create a SelectListItem to display in your dropdownlist.
Example:
#Html.DropDownListFor(model => model.YearStartedToPay,
Enumerable.Range(DateTime.Today.Year - 60, 61).OrderByDescending(x => int.Parse(x.ToString())).Select(n => new SelectListItem() { Text = n.ToString(), Value = n.ToString(), Selected = false }).ToList<SelectListItem>(),....)
In this case, I'm creating an Enumerable, that will be your list returned from EF, ordering and selecting as a SelectListItem.
You need to make use of dropdownlist's Value property. Make your list a type of SelectListItem.
Assign Text= [Your Required Text] and Value = [Current Name]
I have a list created from a controller which is passed to a viewbag item:
List<SelectListItem> PTL = new List<SelectListItem>();
List<PT> PTL2 = db.PT.ToList();
foreach (var item in PTL2)
{
PTL.Add(new SelectListItem { Value = item.ID.ToString(), Text = item.Name });
}
ViewBag.PTL2 = PTL2;
Then, in the view, I tried the following from another question here:
#Html.DropDownList("test", new SelectListItem[]{
new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}}
, htmlAttributes: new { #class = "form-control" })
which worked fine, but, if I try to edit it to the following:
#Html.DropDownList("test", ViewBag.PTL2, htmlAttributes: new { #class = "form-control" })
I get various errors.
I have spent hours on this trying different combinations, different castings and more, but, I just don't seem to be making progress.
I have seen so many different errors - the most common one being '
There is no ViewData item of type IEnumerable<SelectListItem> that
has the key “test”'
However, I tried casting and changing the name as per different questions here, but, I just can't seem to get past this.
At this point, I am thinking of just making a manual HTML Drop Down list and a foreach loop for the content, but, this seems a waste.
Does anyone know what I have done wrong?
The second parameter must be a collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list. But, you are using ViewBag property in this case and the type of this is dynamic. So, you must cast it to the collection of the SelectListItem. Otherwise, you will get this error in MVC 4+:
Extension methods cannot be dynamically dispatched
So. as a result just change
ViewBag.PTL2
to
ViewBag.PTL2 as IEnumerable<SelectListItem>.
i hope it is not too late ,this is how i do it with .net core
in your controller ,use below code
public ActionResult ShowCalendar()
{
var programs = new Microsoft.AspNetCore.Mvc.Rendering.SelectList((new Programs().GetAll().ToList(), "ID", "Name")
ViewBag.AllItems = programs;
return View();
}
and in your cshtml file use the below
<select id="ItemID" class="form-control"
asp-items="ViewBag.AllItems">
<option disabled selected>--- #Localizer["PleaseSelect"] ---</option>
</select>
will do the job for you
I have a view which has a model that is an IEnumerable. I use DropDownListFor Html helper in a foreach loop to output dropdown lists. But it doesn't set the selected item to true. Code as below:
#model IEnumerable<Example>
#foreach (var item in Model) {
#Html.DropDownListFor(modelItem => item.FilePath, (IEnumerable<SelectListItem>)ViewBag.ConfigFiles, string.Empty, null)
}
The above code output a Html select element. But none of the options are selected even though the item.FilePath has the same value as one of the options.
This is an unfortunate limitation of using DropDownListFor() in a loop, and you need to generate a new SelectList in each iteration. However, your use of a foreach loop to generate the form controls will not work. Its creating duplicate name attributes which have no relationship to your model therefore will not bind, and its also generating duplicate id attributes which is invalid html.
Change your model to IList<T> and use a for loop and generate a new SelectList in each iteration using the constructor that sets the selectedValue
#model IList<Example>
....
#for(int i = 0; i < Model.Count; i++)
{
#Html.DropDownListFor(m => m[i].FilePath, new SelectList(ViewBag.ConfigFiles, "Value", "Text", Model[i].FilePath), string.Empty, null)
}
Note that this now generate name attributes which binds to your model
<select name="[0].FilePath">....<select>
<select name="[1].FilePath">....<select>
.... etc
Note that its not necessary to create IEnumerable<SelectListItem> in the controller. Your could instead assign a collection of your objects to ViewBag
ViewBag.ConfigFiles = db.ConfigFiles;
and in the view
new SelectList(ViewBag.ConfigFiles, "ID", "Name") // adjust 2nd and 3rd parameters to suit your property names
In my ViewBag there is object that contains Id,First name and Last name. I want to display DropDownList that has Id as value and "First name"+" "+"Last Name" as text.
#Html.DropDownListFor(model => model.Id, new SelectList(ViewBag.person, "Id","Last Name"), new { #class = "form-control" })
This is the line of code that I use currently, how can I modify it to display the right info?
You have to modify your controller and model to send the concatenated text to the View, or create a new SelectList in the View itself that concatenates the values before passing it to the DropdownListFor.
What you are trying to achieve would be possible if SelectList had an overload with a callback for formatting, but this isn't possible.
I am new to MVC and trying a test application to get my feet wet. Part of this application is to generate a form with a drop down box. I use the
#Html.DropDownListFor() to generate this, and on the create form the drop down works fine. But when I go to the edit form the model value is not passing to the drop down.
SelectList Item
public static string[] OnOffList()
{
var ret = new string[] { "On", "Off" };
return ret;
}
Form code
#Html.DropDownListFor(model => model.ServiceCondition, new SelectList(OnOffDropDownHelper.OnOffList()))
For this instance assume that model.ServiceCondition = "Off".
For some reason whenever I call this form the dropdown value is always "On", it seems to be completely ignoring the model value.
I have also tried this
#Html.DropDownListFor(model => model.ServiceCondition, new SelectList(OnOffDropDownHelper.OnOffList(), "Off"))
to mandate the "Off" value, but it is still coming up as "On" as the selected value in the drop down.
I would like to reiterate, I do know that the model value is "Off", and I created an identical "Create" form using the same #Html.DropDownListFor() and it was able to pass the value to the model just fine.
Like I said, I am new to MVC so any help would be greatly appreciated.
Thanks.
I think you have to set the IsSelected property. This always works for me:
First, just put a property in your model to tidy up the View code:
public List<SelectListItem> OnOffDDL
{
get
{
return OnOffDropDownHelper.OnOffList()
.Select(s => new SelectListItem
{
Text = s,
Value = s,
Selected = ServiceCondition == s
})
.ToList();
}
}
Then do:
#Html.DropDownListFor(model => model.ServiceCondition, model.OnOffDDL)
This may be a little overkill, but is helpful if your model could have different options based on the model itself (even though for now it is just On and Off). Like in the future if certain items could have a "Standby" mode, etc, where you would be getting the actual options from a database for that particular item.
Use a SelectList for the source, so your Model could have:
public List<SelectListItem> OnOffList{ get; set; }
Then populating the Model in your controller like:
model.OnOffList.Add(new SelectListItem()
{
Text = "On",
Value = "On"
});
...etc.
Then you can set the selected item like:
#Html.DropDownListFor(m => m.ServiceCondition, new SelectList(Model.OnOffList(), "Value", "Text", Model.ServiceCondition))
Turns out to be a rookie mistake on my part.
Who ever designed the databese had the field ServiceCondition as nchar(8) leaving white space at the end of the "on ", "Off " values.
A .Trim() in the field in question fixed the issue.
Thanks a ton for the help.