MVC3 - dropdown list to show stored value - asp.net-mvc-3

I have an update page, there is a field call ingredientname, the dropdown lists all the ingredients, but how do I bind the value stored against in each ingredient for a recipe.
In my controller I have the following code which will list all ingredients in dropdown;
foreach (RecipeIngredient recipeIngredient in recipe.RecipeIngredientList)
{
rIngredients.Add(recipeIngredient);
}
on the update page I want the text box to show a value.

<%: Html.DropDownList("BusinessTypeId", new SelectList(Model.BusinessTypes, "BusinessTypeId", "BusinessTypeName"), "Select an Option")%>
Here the value is BusinessTypeId and name is BusinessTypeName
foreach (BusinessType businessType in _businessDetails.BusinessTypes)
{
businessType.BusinessTypeName = businessType.SpanishBusinessTypeName;
businessTypeLst.Add(businessType);
}
//Page
var _ddValue = $('#BusinessTypeId').val();
assign it to textbox
$('#txtboxId').val(_ddValue );

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

display the selected value from DropDown in a page

Hi Folks i am retrieving Name from database to drop down list. Now i want to display the selected value from DropDown in a page. My code is like follows to retrieve data,am using Fluent data as a framework.
My Controller Action is
var query = Abc.GetProducts();
ViewBag.EnterpriseId = new SelectList(query.AsEnumerable(), "EnterpriseId", "Name");
return View();
My view is ,
#Html.DropDownList("EnterpriseID", (SelectList) ViewBag.EnterpriseID, "--Select Resource--")
You can use a simple js for this:
elem = $('.selectClass');
options = elem.find('option[value="'+DataFromDBHere+'"]');
if(options){
options.prop('selected', 'selected');
}

Loop through IEnumerable in #Html.DropDownListFor (MVC3)

I have a collection of models that I am passing to my view and I want to display each model.property in the dropdownlist. The problem is there is a bug in my code where it shows two duplicate items.
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#Html.Label("BRAD Module:")&nbsp
#Html.DropDownListFor(model => model.FirstOrDefault().module_name, Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name }), new { id = "ddlSelectedBrad", onchange = "chkSelection()" })
I am currently using FirstOrDefault() to access the module name for each model in my collection of models. But by doing this I have a duplicate value.
See screenshots below:
MARKET:LEISURE is showing twice
Intelligence is showing twice. If I change this dropdown value and return to this screen it will show two duplicate values.
Summary
Does anyone know a better way of writing the LINQ query?
Thanks.
Instead of
Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name })
Try
Model.GroupBy(x => x.module_name).Select(x => new SelectListItem { Text = x.First().module_name, Value = x.First().module_name })
This should filter the duplicate records.

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)

DropDown for Edit() [Razor]View, Pre-Loaded with Data from Model

I have the dropdowns in my Create() View working perfect.
But in the Edit() View I can't get the Data that was submited during the Create() to show up in DropDowns with the Value enterened upon Create()
I just have textboxs in place at the moment And would really like to have Data Represented in a dropdown for easy selection.
Here is one example:
Create() View - One dropdown is for EmployeeTypes, and stores selected to EmployeeTypeId
Now How do I get that to show up in the Edit() View as the same dropdown, but with Value of EmployeeId already selected?
I have a EmployeeViewModel for the Create() View
But I am just passing the model directly into the Edit() View
Should I create some kind of Employee "partial class" for the Edit() View? to handle the IEnumerable Lists?
and set:
var employeeTypes = context.EmployeeTypes.Select(et => new SelectListItem
{
Value = et.EmployeeTypeId.ToString(),
Text = et.Type.ToString()
});
Or should I pass them in as ViewData?
If so how to do you pass a List in as ViewData and get it to display as an #Html.DropDownList with the Value passed in from the #Model as the defualt value?
I ended up implimenting this way, and it worked like a dream.
Controller Code:
SelectList typelist = new SelectList(context.CompanyType.ToList(), "CompanyTypeId", "Type", context.CompanyType);
ViewData["CompanyTypes"] = typelist;
View Code:
#Html.DropDownList("CompanyTypeId", (IEnumerable<SelectListItem>) ViewData["CompanyTypes"])
There may be bugs in this code - I haven't tested it - but what you basically want to do is:
var etId = ??? // EmployeeTypeId from your model
var employeeTypes = context.EmployeeTypes.Select(et => new SelectListItem
{
Value = et.EmployeeTypeId.ToString(),
Text = et.Type.ToString(),
Selected = et.EmployeeTypeId == etId
});
ViewData["EmployeeTypeList"] = employeeTypes.ToList();
Then in your view you can do
#Html.DropDownList("EmployeeType", ViewData["EmployeeTypeList"])

Resources