html helper html.dropdownlist in asp.net mvc - drop-down-menu

give me full demonstration of html.dropdownlist
how it is implimented?
how to set values in the list?
how to use it in .aspx and in controller file?

Ok, let me have a try
There is SelectList class that you can use to create a list in the controller class (in the approriate controller action) as follows:
var items = new KeyValueList();
var item = new KeyValue() {Key = 1, Value = "Orange" };
items.Add(item);
item = new KeyValue() {Key = 2, Value = "Apple" };
items.Add(item);
var myList = new SelectList(items, "Key", "Value", selectedItemId);
The selectedItemId will be the value of an item's key. Then add myList to the ViewData collection with a key that you can use to refer to it from the View. Like:
ViewData["FruitList"] = myList;
In the View, you can then use:
<p>
<label for="FruitList">Fruits:</label>
<%= Html.DropDownList("FruitList") %>
</p>
On postback to the controller action, the "Key" for the selected value is sent as part of formcollection or post parameters, and you can access the value using the "FruitList".

Related

DropDownList Initial Value Duplicated - MVC 5

I have a #foreach in my View that makes a table. Each row has two items within it's td. When I click my Edit button, the visible item's in a row disappear (DislayFor's) and the hidden items in the row appear (DropDownList)
View Code
<td class="col-md-3">
<span class="item-display">
<span style="font-size: 17px">
#Html.DisplayFor(modelItem => item.Movie.Name)
</span>
</span>
<span class="item-field">
#Html.DropDownList("movieID", item.Movie.Name)
</span>
</td>
By doing this I can select a new value in the DropDownList and then Save that change to my Database (then hiding the DropDownList and unhiding the DisplayFor.
Everything works fine, however I have an issue with the initally selected value, it appears twice with the initial value having an actual value of 0 (which relates to nothing in the DB).
Picture Example
QUESTION:
Right now my dropdown add's a value upon clicking Edit, the item initially selected has the correct name but it is given the index of 0 (which is invalid for my database).
I want to have the initially selected item to NOT be added, but rather to set the selector of the dropdown to the CORRECT INDEX of the appropriate item. I am not sure why it duplicates my selected item twice.
Controller Code
public ActionResult Index(string Filter, string searchString)
{
if (String.IsNullOrEmpty(searchString) || String.IsNullOrEmpty(Filter) || (Int32.Parse(Filter) == 0))
{
ViewBag.employeeID = new SelectList(db.Employees, "ID", "Name", );
ViewBag.movieID = new SelectList(db.Movies, "ID", "Name", initiallySelectedValue);
ViewBag.roleID = new SelectList(db.Roles, "ID", "RoleType");
var movieemployees = db.MovieEmployees.Include(m => m.Employee).Include(m => m.Movie).Include(m => m.Role);
return View(movieemployees.ToList().OrderBy(x => x.Employee.Name));
}
else
{
ViewBag.employeeID = new SelectList(db.Employees, "ID", "Name");
ViewBag.movieID = new SelectList(db.Movies, "ID", "Name");
ViewBag.roleID = new SelectList(db.Roles, "ID", "RoleType");
var parameter = Int32.Parse(Filter);
return View(db.MovieEmployees.Include(m => m.Employee).Include(m => m.Movie).Include(m => m.Role).Where(x => (parameter == 1 && x.Movie.Name.Contains(searchString)) || (parameter == 2 && x.Employee.Name.Contains(searchString)) || (parameter == 3 && x.Role.RoleType.Contains(searchString))).Distinct().ToList().OrderBy(x => x.Employee.Name));
}
}
Your understanding of the parameters for DropDownList isn't quite correct, but you're close! The second parameter for DropDownList (in your case item.Movie.Name) is adding an option label. If you replaced that with a hard-coded string that would serve as a good example of what it's doing (you would see that string as the first option of every select input).
It sounds to me like you want to delete that last parameter since it will only end up serving as a duplicate. Your code would simply look like this:
#Html.DropDownList("movieID")
The important part of your code is where you're building the object that you're storing in ViewData with the key movieID. You didn't post your controller code, but I imagine it looks something like:
var movies = movieRepository.GetAllMovies();
ViewData["movieID"] = new SelectList(movies, "Name", "Id", initiallySelectedValue);
Where Name and Id are the names of properties on the movie object and initiallySelectedValue is rather self explanatory.
Edit
Here is an example of how I would go about solving your problem:
Controller
public ActionResult Index() {
//Get all the possible movies that can be selected
var movies = movieRepository.GetAllMovies();
//Get a list of employees with their related favorite movie record
var employeesWithFavoriteMovie = movieRepository.GetEmployeesWithMovie();
var employeeModels = new List<EmployeeModel>();
//Iterate through the list of employees and their favorite movie, and build the model
foreach (var employeeWithFavoriteMovie in employeesWithFavoriteMovie) {
employeeModels.Add(new EmployeeModel() {
FirstName = employeeWithFavoriteMovie.FirstName,
FavoriteMovieId = employeeWithFavoriteMovie.Movie.Id,
MovieSelectList = new SelectList(movies, "Name", "Id", employeeWithFavoriteMovie.Movie.Id)
});
}
return View(employeeModels);
}
View
#model IEnumerable<WebApplication1.Controllers.EmployeeModel>
#foreach (var employeeModel in Model) {
#Html.DropDownList("Test", employeeModel.MovieSelectList)
}
Notice how a SelectList was built for each employee and that each list is then populated with that employees current favorite movie id. This will now put you in a position to have a properly built SelectList for each employee.
#Html.DropDownListFor(model => model.classmasterd_HCF[i].TD_TEACHER, new SelectList(Model.Teacher, "ParamKey", "ParamValue", Model.classmasterd_HCF[i].TD_TEACHER) as SelectList, new { #class = "form-control input-sm DtlField EditableCtrl", #style = "min-width:100%;", #disabled = "disabled" })
where Teacher in Model.Teacher is a model with code in paramKey and description in paramvalue. Selected value saved in TD_TEACHER field

Editing form with dropdownlist, showing value in dropdownlist

I have editing form with dropdownlist. It's work properly but when I'm on a editin page, in dropdownlist I see first value from a list. I want make, I can see value which I have in database. ex. I have company: 1, 2, 3, 4, 5, and when I editing I have default company 1. But in databese for this product is company 4. Do if I will editin form in dropdownlist I would like have defoult showing company 4 instead 1.
I hope you understand what I have on the mind.
Controller:
[HttpGet]
public ActionResult edytuj_prod(int ID_Produkt)
{
var prod = (from d in baza.Produkts
join s in baza.Firmas on d.ID_firma equals s.ID_firma where ID_Produkt == d.ID_Produkt
select new { d.ID_firma, d.nazwa_prod, d.ilosc, d.jednostka, d.cena, d.ID_Produkt, s.nazwa }).First();
var firma = baza.Firmas;
produktModel pr = new produktModel()
{
firmaList = firma.AsEnumerable().Select(x => new SelectListItem
{
Value = x.ID_firma.ToString(),
Text = x.nazwa
})
};
pr.nazwa_prod = prod.nazwa_prod;
pr.ilosc = prod.ilosc;
pr.jednostka = prod.jednostka;
pr.cena = prod.cena;
return View(pr);
View:
<div class="editor-field">
#Html.DropDownListFor(x => x.ID_firma, Model.firmaList)
</div>
If I understood correctly, you want the dropdown list to have the saved item selected instead of having the first item on the list. If so, see this answer
Also you could check these constructors:
public SelectList(IEnumerable items, Object selectedValue)
public SelectList(IEnumerable items, string dataValueField, string dataTextField, Object selectedValue)

dropdownlist for following

var dropdown = (from role in db.aspnet_Users
where role.aspnet_Roles.Any(a => a.RoleName == "supervisor")
select new
{
text = role.UserName,
value = role.UserId
}).ToList();
code to generate dropdown list having dropdown.text as DropdownList item/text and dropdown.value as DropdownList value
This code Present in my view.cshtml
using razor:
#Html.DropDownList("name",
new SelectList( dropdown ,
"value",
"text" ) )
where dropdown is your variable
Also considering moving your code to the controller and passing the variable through viewbag (ie: ViewBag.dropdownitems = dropdown)

Html.DropDownListFor does not bind boolean SelectList

I have this code the constructs a select list as a boolean response
var responseList = new List<SelectListItem>();
responseList.Add(new SelectListItem { Text = "Going", Value = bool.TrueString});
responseList.Add(new SelectListItem { Text = "Not Going", Value = bool.FalseString });
ViewData[ViewDataKeys.ResponseTo] = vatOptionList;
In my view I use the dropdownlist helper below.
#Html.DropDownListFor(m => m.ResponseTo, (IEnumerable<SelectListItem>)ViewData[ViewDataKeys.ResponseTo], "--Select--")
this is the property on my Model class:
[Display(Name = "Response To")]
public bool ResponseTo { get; set; }
My problem is that what ever the value of my model.ResponseTo is, the dropdownlist always select the optional value.
I tried to use a checkbox helper and surprisingly it doesn't appear to be checked alse, though when I inspected the element, the checkbox value is "true"
I tried to use a textbox helper and it shows a "true" text, Which I think that my model has value and it just doesn't bind to the dropdownlist or checkbox. I need to use a dropdownlist. Anything I missed out?
Just tested this, it works:
In your action method:
var selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "Going", Value = bool.TrueString });
selectListItems.Add(new SelectListItem { Text = "Not going", Value = bool.FalseString });
ViewBag.MySelectList = new SelectList(selectListItems, "Value", "Text", viewModel.IsGoing);
In your view:
#Html.DropDownList("IsGoing", (SelectList) ViewBag.MySelectList)

MVC DropDownListFor() Selected Item is not Selected / Required Validation not run

I am having trouble getting my DropDownList to set the selected item to the value from the model.
The field in the model is just a string for the Title of the users name (Mr, Miss etc..) Below is my code so far.
<td>
#{ var list = new List<SelectListItem>(new[] {
new SelectListItem{ Selected = string.IsNullOrEmpty(Model.Title), Text="",Value=""},
new SelectListItem{ Selected = Model.Title.Equals("Mr"), Text="Mr",Value="Mr"},
new SelectListItem{ Selected = Model.Title.Equals("Mrs"), Text="Mrs",Value="Mrs"},
new SelectListItem{ Selected = Model.Title.Equals("Miss"), Text="Miss",Value="Miss"},
new SelectListItem{Selected = Model.Title.Equals("Ms"), Text="Ms",Value="Ms"}
});
}
#Html.DropDownListFor(m=>m.Title, list)
</td>
I had this problem with MVC 3 and it turned out that I had set ViewBag.Title on my View (using it for the page title). As soon as I changed it to ViewBag.PageTitle, the dropdownlist code started working : #Html.DropDownListFor(model => model.Title, Model.MySelectList)
The reason for this is that in MVC 2/3, any ViewBag / ViewData properties with the same name as those in the Model object get used in preference in DropDownListFor(), so you need to rename them to make sure they don't conflict. Because that seems really flaky, I just stopped using ViewBag entirely and now rely only on the View Model for passing stuff into the View.
The reason this problem is so prevalent is that ViewBag.Title is used in many introductory tutorials and demo code to set the HTML title element, and so inevitably gets adopted as a "best-practice" approach. However, Title is a natural Model property name for use in dropdowns on a "User Details" view.
So it turns out that the only reason it doesn't work is because my field name is Title, I changed it to Prefix and my exact code works. Way too much time spent finding that out...
Here is working code.
<td>
#{ var list = new List<SelectListItem>(new[] {
new SelectListItem {
Selected = string.IsNullOrEmpty(Model.Prefix),
Text="",
Value=""
},
new SelectListItem {
Selected = Model.Prefix.Equals("Mr"),
Text="Mr",
Value="Mr"
},
new SelectListItem {
Selected = Model.Prefix.Equals("Mrs"),
Text="Mrs",
Value="Mrs"
},
new SelectListItem {
Selected = Model.Prefix.Equals("Miss"),
Text="Miss",
Value="Miss"
},
new SelectListItem {
Selected = Model.Prefix.Equals("Ms"),
Text="Ms",
Value="Ms"
}
});
}
#Html.DropDownListFor(m => m.Prefix, list)
</td>

Resources