ASP.NET MVC dropdown with a default empty option - asp.net-mvc

Is there a way to include a default empty option (or with text) if there is no selected value for a dropdownlist?

The below will prepend string.Empty to the SelectList (or IEnumerable) specified in the ViewData["Menu"] item. The select will have id and name MenuID.
<%= Html.DropDownList( "MenuID",
(IEnumerable<SelectListItem>)ViewData["Menu"],
string.Empty ) %>
Documentation: DropDownList method

For Example:
Controller :
private void InitScreenInfoCollate()
{
IEnumerable<MstBrd> listbrd = ibrandRepository.GetItemsByUsercode("");
ViewBag.Brands = new SelectList(listbrd, "brd_cod", "brd_mei", null);
}
View :
#Html.DropDownList("Brands", null, string.Empty, new { #class = "form-control"})
Result :

This easy solution worked for my mvc5 project:
in view:
#{
Model.ModelItemsList.Add(new ModelItem{ });
SelectList modelItemSelectList = new SelectList(Model.ModelItemsList, "ModelItemID", "ModelItemName");
}
Just add a new item to the List<> you want to display in your view.
In my case, I added a empty "ModelItem" to my List<ModelItem> ModelItemList. Since my ModelItemID is a Guid, I had to check for Guid.Empty in my controller method and do some code.
Thats all.

The solution presented here worked very well for me: http://forums.asp.net/t/1142484.aspx/1
The basic idea is that you set the AppendDataBoundItems property of your DropDownList to true and then put an asp:ListItem in the DropDownList and that will become your default item with all the databound items coming after it.

Related

selectedValue from view to controller MVC

Filter records in index view using dropdown list . How replace xxxxxxx with selectedValue from dropdownlist to filter. I am not sure how to select the selectedValue from dropdown list in the view. The controller code and the view code is below. I know its a small problem. But I am trying to find for some hours.The filter is working fine if i replace with xxxxxx with 1 , 2 etc.But I want to change xxxxx with selectedValue from Dropdown list.
controller code
ViewBag.doctorsid = new SelectList(db.doctors, "doctorsid", "doctorsname",selectedValue);
return View(appointments.Where(d => d.doctorsid == xxxxxxx).ToList());
view code
#Html.DropDownList("Doctorsid","Select Doctor")
Use script given bellow
Script
$("#Doctorsid").change(function () {
var doctorsid = $('#Doctorsid').val();
var url = "/ControllerNmae/ActionResultName/+doctorsid ;
window.location.href = url;
});
Use a Model with variables for list and drop down value instead of passing list directly to view
Controller:
ViewBag.ClientTypeID = new SelectList(db.ClientType.Where(ct => ct.IsDeleted != true), "ID", "ClientTypeName");
View:
#Html.DropDownListFor(m => m.ClientTypeID, new SelectList(ViewBag.ClientTypeList, "Value", "Text"), new { #class="drop"})

Setting a preselected item for html.dropdownlistfor

I have a a html.dropdownlistfor which list around 900 items
Html.DropDownListFor(m => m.ParentWebContentID, null, "Choose...", htmlAttributes: new { #class = "form-control" })
I want it to have a preselected item and thought the 3rd parameter ("Choose...") was for this.
So I arranged for a ViewBag variable to hold a value (ChosenParentWebContentId)
like this
public ActionResult Create(int? id)
{
if (!AccountController.IsInRole(System.Web.HttpContext.Current.User.Identity.Name, "admin"))
{
return RedirectToAction("Index");
}
ViewBag.ParentWebContentID = GetWebContentListwithGroup(null);
if(id != null)
{
ViewBag.ChosenParentWebContentID = db.WebContent.FirstOrDefault(x => x.WebContentID == id).ParentWebContentID;
}
ViewBag.WebContentTypeID = db.WebContentType.ToList();
ViewBag.ContentTypeID = id;
ViewBag.LanguageCode = new SelectList(db.WebLanguage, "LanguageCode", "DisplayName");
ViewBag.CreatedByUserID = new SelectList(db.AspNetUsers, "Id", "Email");
ViewBag.LastEditedByUserID = new SelectList(db.AspNetUsers, "Id", "Email");
ViewBag.DetailList = db.WebContentDetail.Where(x => x.WebContentID == id).ToList();
return View();
}
I tried changing "choose..." with the ViewBag variable but it didn't work. Is there any other way to do this?
I couldn't find any help on other examples around internet.
When you use Html.DropDownListFor (or any of the *For family of helpers), the value comes from the value of the bound property. Actually, it's a little more complex than that. The value comes from the value of the bound property in ModelState.
So, if you want an item to be automatically selected, then you need to set ParentWebContentID to the value you want selected. Plain and simple. However, once a post is made, the select value will always be what was posted, even if you set ParentWebContentID to a different value. Also worth bearing in mind: Request, ViewBag and ViewData all participate in defining the values in ModelState. As a result, if for example you had an action that had a param named parentWebContentID (case-insensitive), that value from the request would always take precedence over any value you set on the model explicitly.

MVC dropdownlist in View setting selected Value

I'm trying to set the selected Value for a drop down list.
In Controller I have
ViewData["productType"] = new SelectList(myDropDownList);
And in the View:
<%= Html.DropDownList("productType", ViewData["productType"] as SelectList, "defaultValue")%>
So far So good, but the problem is that now I have "defaultValue" twice in my drop down list. so I have all my values in dropdownlist including the "defaultValue". but this code will add the "defaultValue" as the first element. and I see two samples of it.
I like to set the selected valiue to "defaultValue" without adding it twice.
I tried
ViewData["productType"] = new SelectList(myDropDownList, "defaultValue" );
but it didn't work.
Can anyone please tell me what to do?
You should not be using the same name as first argument for the dropdown as the second one. In your example you have used productType for storing both the selected value and the list of available values. In order to render a DropDown in ASP.NET MVC you need 2 properties:
<%= Html.DropDownList(
"selectedProductType",
ViewData["productType"] as SelectList,
"defaultValue"
) %>
and inside your controller action you could set those 2 properties:
ViewData["selectedProductType"] = "abc";
ViewData["productType"] = new SelectList(myDropDownList);
this assumes that you already have an element with value="abc" inside your dropdown list of product types. The value will then be automatically preselected.
I would recommend you an alternative approach though for rendering dropdown lists. It consists of getting rid of view data and introducing view models and using the strongly typed version of the helper:
public class ProductViewModel
{
public string SelectedProductType { get; set; }
public IEnumerable<SelectListItem> ProductTypes { get; set; }
}
then you will have a controller action that will populate this view model and pass it to the view:
public ActionResult SomeAction()
{
var model = new ProductViewModel();
// preselected an element with value = "type2"
model.SelectedProductType = "type2";
// bind the available product types
model.ProductTypes = new SelectList(
// Obviously those could come from a database or something
new[] {
new { Value = "type1", Text = "product type 1" },
new { Value = "type2", Text = "product type 2" },
new { Value = "type3", Text = "product type 3" },
new { Value = "type4", Text = "product type 4" },
},
"Value",
"Text"
);
// pass the view model to the view
return View(model);
}
and finally inside your strongly typed view:
<%= Html.DropDownListFor(
x => x.SelectedProductType,
Model.ProductTypes,
"defaultValue"
) %>

Should I send select list data to the view or let it get the data itself?

I have a create method in my controller and this opens up a view. On the view the user can enter data to populate the model. Some of that data comes from select lists. These select lists are populated from the database.
What I would like to know is should I:
a) Get data for the select lists in the controller, populate a field like this:
public IEnumerable<SelectListItem> Statuses { get { return GetStatusType(); } }
pass Statuses to the model and then do a for () to loop through statuses and create a select list and options HTML
b) Do nothing in the controller and in the view have the following in the model:
<select id="Q_StatusID" name="Q.StatusID">#Html.Raw(
SelectHelper.Status(false, #Model.PageMeta.StatusID))</select>
Where the SelectHelper is C# code that gets all the select list and options HTML.
c) Some better way:
I would go with the first one. some thing like this
a helper method
public List<SelectListItem> getAllSelectList(List<Items> lists)
{
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (Term term in lists)
{
selectListItems.Add(new SelectListItem() { Text = term.yourselectfield, Value = term.your value });
}
return selectListItems;
}
on your controller
//assuming you GetStatusType() method will return list of objects
ViewData.selectlist=getAllSelectList(GetStatusType());
on your view, if you are using Razor
#Html.DropDownList("selectlist", null, "Choose")
or
<%: Html.DropDownList("selectlist", null, "Choose") %>
Create a static Look-up class & static method for your GetStatusType there.
Cache all the status types after first time loading from your database.
Call GetAllStatusType from the view to display.
I would create a view model, which has a IEnumerable< Statuses > property. Then in your view to display the select element :
#Html.DropDownListFor(model => model.PageMeta.StatusID, new SelectList(Model.Statuses, "Id", "Name"), "Some default which has no value")
Where Id and Name are set to the appropriate properties in your Statuses model.

Add option to droplist

I have a droplist, and I would like to add an All as the first one.
How is that done with asp.net mvc?
I have:
<%= Html.DropDownList("selCustomerID") %>
works great, but I don't have an empty "all-option". I populate it like this:
return View("Index", new CustomerAdminEditViewModel { selCustomerID = new SelectList(_cs.GetCustomers(), "CustomerID", "CustomerName") });
Check this link : http://forums.asp.net/t/1429075.aspx
It is talking about an optional label parameter in the constructor.

Resources