I currently have the below snippet of code that works fine for Dropdown list. I would like to do the same thing but have it as a TextBoxFor field instead. I am utilizing bloodhound bootstrap plugin and replacing my dropdown list with the bootstrap plugin.
#Html.DropDownListFor(m => m.CaseMaster.InvoiceStatusId, new SelectList(Model.InvoiceStatus, "Id", "Name"), "Select Status", new { #class = "form-control col-sm" })
Related
This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 6 years ago.
I'm trying to implement a Dropdownlist that displays data from database. The code for my implementation is as follows:
View
<div class="form-group">
#Html.Label("Select Your User Type", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Drop")
</div>
</div>
Controller
ViewBag.Drop = new SelectList(db.Roles, "Name", "Name");
I have checked that many online tutorials uses this method. However, whenever I try to save the information, it gives off the error as follows:
I checked the datatype for the ViewBag.Drop and it was System.Web.Mvc.SelectListItem datatype instead of the IEnumerable<SelectListItem needed for the Html.DropDownlist helper function.
What should I do and how come it changes the type to System.Web.Mvc.SelectListItem???
You changed the type when you created the list as a SelectList.
What would happen if you did this?:
[ Controller ]
var Drop = db.Roles.ToList();
ViewBag.Drop = Drop;
[ View ]
#Html.DropDownListFor(model => model.RoleName, new SelectList(#ViewBag.Drop, "Name", "Name"), new { htmlAttributes = new { #class = "form-control" } })
Where the Drop declaration creates an IEnumerable List of IdentityRole, and it's passed to the View via the ViewBag. Where (assuming if you're using a ViewModel with a property named RoleName), you would be selecting the value for the RoleName from the List.
Here you're creating a SelectList and telling it what member of the Drop list to use for the value and what member value to show for selection.
I have created a DropDwonList in MVC like this
#Html.DropDownListFor(x => x.Item2.DeliveryDetail.PackageTypeId, new SelectList(lstPackageTypes, "PackageTypeId", "PackageTypeName"),new {#class = "cstm-input", #placeholder = "Package Type"})
It generates a DropDown but by default the first Item is selected when page loads. I want that the dropdown should be un-selected and the user should be allowed to select a value from it.
Thanx in Advance.
You can specify the default OptionLabel with overload method of DropDownListFor as below:
#Html.DropDownListFor(x => x.Item2.DeliveryDetail.PackageTypeId,
new SelectList(lstPackageTypes, "PackageTypeId", "PackageTypeName"),
"--Select Package Type--",
new {#class = "cstm-input", #placeholder = "Package Type"})
I'm trying to create an Item edit screen where the user can set a property of the Item, the ItemType. Ideally, when the user returns to the screen, the dropdown would display the ItemType already associated with the Item.
As it is, regardless of what the item.ItemType is, the dropdown will not reflect that in the dropdown. Is there a way around this?
For reference, my code at the moment is:
<div class="form-group">
#Html.LabelFor(model => model.ItemType, new { #class = "control-label col-xs-4" })
<div class="col-xs-8">
#Html.DropDownListFor(model => model.ItemType, (SelectList)ViewBag.ItemType, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemType, String.Empty, new { #class = "text-danger" })
</div>
</div>
The ViewBag is set with the following:
var ItemType = Enum.GetValues(typeof(ItemType));
ViewBag.ItemType = new SelectList(ItemType);
If you're using ASP.NET MVC 5, try just using the EnumHelper.GetSelectList method. Then you don't need ViewBag.ItemType.
#Html.DropDownListFor(model => model.ItemType, EnumHelper.GetSelectList(typeof(ItemType)), new { #class = "form-control" })
If not, you might need to specify the data value and data text fields of the select list.
var itemTypes = (from ItemType i in Enum.GetValues(typeof(ItemType))
select new SelectListItem { Text = i.ToString(), Value = i.ToString() }).ToList();
ViewBag.ItemType = itemTypes;
Then since it's an IEnumerable<SelectListItem> you'll need to change your cast.
#Html.DropDownListFor(model => model.ItemType, (IEnumerable<SelectListItem>)ViewBag.ItemType, new { #class = "form-control" })
Eventually I found a fix - manual creation of the list.
<select class="form-control valid" data-val="true"
data-val-required="The Item Type field is required." id="ItemType" name="ItemType"
aria-required="true" aria-invalid="false" aria-describedby="ItemType-error">
#foreach(var item in (IEnumerable<SelectListItem>)ViewBag.ItemType)
{
<option value="#item.Value" #(item.Selected ? "selected" : "")>#item.Text</option>
}
</select>
Try to keep as much of the logic outside of the View and in the Controller.
I saw in your self answer that it looks like you have an enum selected from wihin your controller.
I have a DropDownList in one of my apps that contains a list of Enums. It also has a default value selected, but also has specific enums available to the user. The default selection can be set from within the controller.
This example is based on what my needs were, so you'll need to adapt to your case.
In the controller:
public ActionResult Index()
{
ViewBag.NominationStatuses = GetStatusSelectListForProcessView(status)
}
private SelectList GetStatusSelectListForProcessView(string status)
{
var statuses = new List<NominationStatus>(); //NominationStatus is Enum
statuses.Add(NominationStatus.NotQualified);
statuses.Add(NominationStatus.Sanitized);
statuses.Add(NominationStatus.Eligible);
statuses.Add(NominationStatus.Awarded);
var statusesSelectList = statuses
.Select(s => new SelectListItem
{
Value = s.ToString(),
Text = s.ToString()
});
return new SelectList(statusesSelectList, "Value", "Text", status);
}
In the view:
#Html.DropDownList("Status", (SelectList)ViewBag.NominationStatuses)
This approach will automatically set the default item to the enum that was selected in the controller.
I am using MVC4 and c#. I have a DropDownList which I set using ViewBag.
#Html.DropDownList("category_Parent", new SelectList(ViewBag.Category, "Id", "Name"), new { #class = "form-control" })
By default it always selects the first value but I want it to select a null value (a default value). How can I do this?
I have table called Roles with the following columns: RoleID, RoleName. The rows of the table are :
RoleID RoleName
1 .NET Developer
2 Java Developer
3 Tester
I have another table called Employees with the following columns: EmployeeID, Name, RoleID (a one-to many relationship with the Roles table).The rows of the table are:
EmployeeID Name RoleID
1 John 1
2 Dan 2
In my ASP.NET MVC 5 application I'm doing a CRUD opperation on employees. When I want to add a emploee I will have, besides the Name field, I have a dropdown list with the role that I want to assign. If I want to create a employee everything works well.
My problem is that, when I want to edit a employee my dropdown list does not work as I am expecting. Lets assume that I want to change Dan's role to a Tester (RoleID should be changed from 2 to 3)
I click edit on the Edit view and the selection of the dropdown list is .NET developer (the first entity), although I want to be a Java Developer (the second entity). I know why. I do not know how to fix it.
The Edit method from the controller which I believe is correct is the following:
[HttpGet]
public ActionResult Edit(int id=0)
{
Employee employeeToUpdate = db.Employees.Find(id);
Role selectedRole = employeeToUpdate.Role;
ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName",selectedRole);
return View(employeeToUpdate);
}
The code from the view wich I believe I should modify it but I don't know how is the following:
<div class="form-group">
#Html.LabelFor(model => model.RoleID, "RoleID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("RoleID", null, "The Acctual Employee Role", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.RoleID, "", new { #class = "text-danger" })
</div>
</div>
I can delete the parameter "The Acctual Employee Role" but I will get the list of all roles froom the database without being selected the coresponding role (Java Developer).
I tried, to replace the "The Acctual Employee Role" with a #ViewBag.AcctualRole wich was initialized on the controller. Unfortunately that does not work because I may not use dinamycally expresions there.
Any help will be appreciated!
Change your selectlist to (so it does not have the save name as the property name you are binding to)
ViewBag.RoleList = new SelectList(...
and your dropdown to
#Html.DropDownListFor(m => m.RoleID, (SelectList)ViewBag.RoleList, "The Actual Employee Role", htmlAttributes: new { #class = "form-control" }
The initial selected item will now be the value of employeeToUpdate.RoleID