Include 'ALL' option in dropdownlist bind using ViewBag - asp.net-mvc

I have bind the dropdownlist in view by Viewbag from controller as following :
ViewBag.test = from p in _userRegisterViewModel.GetEmpPrimary().ToList().Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
select new
{
Id = p.EmpId,
Name = p.First_Name.Trim() + " " + p.Last_Name.Trim()
};
In view I have bind as following :
#Html.DropDownListFor(model => model.EmpId, new SelectList(#ViewBag.test, "Id", "Name"),
new { #class = "form-control", id="ddlEmp" })
Now i want to Insert "ALL" and "--Select--" in this dropdownlist.. How can i do this..
Can anyone help me to do this..
Thanks in advance..

You can add a null option to the dropdownlist by using one of the overloads of DropDownlistFor() that accepts a optionLabel, for example
#Html.DropDownListFor(m => m.EmpId, new SelectList(#ViewBag.test, "Id", "Name"), "--select--", new { #class = "form-control", id="ddlEmp" })
which will generate the first option as <option value="">--select--</option>
However, if you want to include options with both "--select--" and "ALL" you will need to generate you own IEnumerable<SelectListItem> in the controller and pass it to the view. I would recommend using view model with a IEnumerable<SelectListItem> property for the options, but using ViewBag, the code in the controller would be
List<SelectListItem> options = _userRegisterViewModel.GetEmpPrimary()
.Where(a => a.UserType_id != Convert.ToInt32(Session["loginUserType"].ToString()))
.Select(a => new SelectListItem
{
Value = a.EmpId.ToString(),
Text = a.First_Name.Trim() + " " + a.Last_Name.Trim()
}).ToList();
// add the 'ALL' option
options.Add(new SelectListItem(){ Value = "-1", Text = "ALL" });
ViewBag.test = options;
Note that I have given the ALL option a value of -1 assuming that none of your EmpId values will be -1
Then in the view, your code to generate the dropdownlist will be
#Html.DropDownListFor(m => m.EmpId, (Ienumerable<SelectListItem>)ViewBag.test, "--select--", new { #class = "form-control" })
Not sure why your wanting to change the id attribute from id="EmpId" to id="ddlEmp"?
Then in the POST method, first check if ModelState is invalid (if the user selected the "--select--" option, a value of null will be posted and the model will be invalid), so return the view (don't forget to reassign the ViewBag.test property).
If ModelState is valid, then check the value of model.EmpId. If its -1, then the user selected "ALL", otherwise they selected a specific option.

Related

Mvc 5 Multiselectlist selected not working

select element created with items in it, but "selected" properties not showing in html result. What i do wrong?
this code is working:
controller:
ViewBag.ProductTwistDirectionID = new SelectList(db.tblProductTwistDirection,
"ProductTwistDirectionID",
"ProductTwistDirectionName",
tblProduct.ProductTwistDirectionID);
view:
#Html.DropDownList("ProductTwistDirectionID",
null,
htmlAttributes: new { #class = "form-control" })
this code is not working: (selected items not selecting at render)
controller:
ViewBag.ProductUsePurposes = new MultiSelectList(db.tblProductUsePurpose,
"ProductUsePurposeID",
"ProductUsePurposeName",
tblProduct.ProductUsePurposes
.Select(x
=> x.ProductUsePurposeID)
.ToArray());
view:
#Html.DropDownListFor(model => model.ProductUsePurposes,
null,
new
{
#class = "chosen-select",
multiple = "multiple",
data_placeholder = "Choose use purposes",
style = "width: 400px;"
})
Your ViewBag member holding the select list cannot be named the same as your model property. ViewBag is used, in addition to ViewData and Request, to compose the ModelState object and whatever is in ModelState overrides the properties on your model.
Simply, you need to rename ViewBag.ProductUsePurposes to something like ViewBag.ProductUsePurposesChoices. Then, you should be fine.

How to work with DropDownListFor in an EDIT view

Hi I have a problem with DropDownListFor on the Edit view.
Basically I'm using a partial view which contains my form and in my Edit and Create view I call this partial view.
I have around 5 similiar DropdownlistFor and these work well on create action but in edit doesn't, mainly i'm not getting (unable) to set the selected value.
In my Edit Action (GET), I fill my property ViewModel if the true object has the property filled.
if(icb.BAOfficer != null)
editICB.BAOfficer = icb.BAOfficer;
List<Staff> staffs = _fireService.GetAllStaffs().ToList();
staffs.Insert(0, new Staff { StaffId = -1, Name = "" });
editICB.BAOfficers = staffs;
return View(editICB);
This is how I'm filling my drop down and how I'm trying to set the selected value.
#Html.DropDownListFor(model => model.BAOfficerSelected, new SelectList(Model.BAOfficers, "StaffId", "Name", (Model.BAOfficer!= null ? Model.BAOfficer.StaffId:-1)), new { #class = "rounded indent" })
#Html.ValidationMessageFor(model => model.BAOfficer.StaffId)
I solve the problem setting a value to my model.BAOfficerSelected in Edit Action, this was the (easy) secret.
I need the first item like a empty option because is not a required information, but on the edit view if has value I need to set it as selected option.
In the end, it was my code.
My Model
public int BAOfficerSelected { get; set; }
public SelectList BAOfficers { get; set; }`
My Controller Create/Edit Action
if (icb.BAOfficer != null) // only for edit action
editICB.BAOfficerSelected = icb.BAOfficer.StaffId; //this will set the selected value like a mapping
//for Edit and Create
List<Staff> staffs = _fireService.GetAllStaffs().ToList();
staffs.Insert(0, new Staff { StaffId = -1, Name = "" });
editICB.BAOfficers = new SelectList(staffs, "StaffId", "Name");
return View(editICB);`
My View
#Html.DropDownListFor(model => model.BAOfficerSelected, Model.BAOfficers, new { #class = "rounded indent" })
I hope this can help others.
The best and cleanest way of doing this is setting the selected value in server side, in the SelectList object.
So, if your BAOfficerSelected is nullable... it is all simpler: You don't need to rely in adding a dummy item to hold the -1 for not selected value.
Instead, you do it this way:
List<Staff> staffs = _fireService.GetAllStaffs().ToList();
editICB.BAOfficers = new SelectList(staffs, "StaffId", "Name", editICB.BAOfficer != null ? editICB.BAOfficer.StaffId : null);
Of course, the BAOfficers need to be changed type from List<Staff> to SelectList.
Then, in your partial view you do:
#Html.DropDownListFor(model => model.BAOfficerSelected, Model.BAOfficers, "Select one...", new { #class = "rounded indent" })
Adding the 3rd parameter is needed to indicate that the default value (if nothing is selected) is that text.
Instead of using a SelectList, I often find it works better to use a List<SelectListItem>.
Further, I usually use an EditorTemplate for my dropdowns to keep my views clean.
So if my select list returns List<SelectListItem>:
public List<SelectListItem> BAOfficers { get; set };
You can set it up like this:
model.BAOfficers = staffs.Select(staff =>
new SelectListItem { Text = staff.Name, Value = staff.StaffId }).ToList();
Then in your EditorTemplate:
<!-- EditorTempaltes\DropDownList.cshtml -->
#model System.String
<p>
#Html.LabelFor(m => m):
#Html.DropDownListFor(m => m, new SelectList(
(List<SelectListItem>)ViewData["selectList"], "Value", "Text",
String.IsNullOrEmpty(Model) ? String.Empty : Model), String.Empty)
#Html.ValidationMessageFor(m => m)
</p>
And then in the view, just pass the SelectList into the EditorTemplate:
#Html.EditorFor(m => m.BAOfficerSelected, "DropDownList",
new { selectList = Model.BAOfficers() })
I met the same problem ,too.
According the article https://dotnetfiddle.net/PIGNLF which way gave a simple way to deal with this problem without two Models or more classes.enter link description here
here is my code
add model
public class NoteSelectLisModel
{
public string Value { get; set; }
public string Name { get; set; }
}
add Controller
public ActionResult Edit(int? _ID)
{
ViewBag.NoteState = new SelectList(new List<NoteSelectLisModel>()
{
new NoteSelectLisModel() {Value="1",Name="A)"},
new NoteSelectLisModel() {Value="2",Name="B"},
new NoteSelectLisModel() {Value ="3",Name ="C"}
}, "Value", "Name", 1);
Table ut = _db.Tables.Find(_ID);
if (ut == null)
{
return HttpNotFound();
}
else
{
return View(ut);
}
}
add View .cshtml
#Html.DropDownListFor(m => m.NOTE, (IEnumerable<SelectListItem>)ViewBag.NoteState, "No Selected")
The edit's Model is the same and the dropdownlist passed by View.bag

Set dropdown item selected MVC

I have multiple dropdown list for same select list in look and want to set dropdown item selected as per loop.
How can I set specific one item of dropdown list selected in mvc dropdownlist.
Please help.
The Html.DropDownList method takes multiple parameters, one of them being a List<SelectListItem>. The individual instance of the SelectListItem is where you set the Selected property:
var item = new SelectListItem() {
Selected = /* condition */,
Value = "Some Value",
Text = "Some Text"
};
Alternatively:
Create a SelectList collection that exposes the SelectedValue property:
Model.YourSelectList = new SelectList(items /* List<SelectListItem> */,
"Value",
"Text",
37 /* selected value */);
When building the SelectList, you can set the selected item on construction using http://msdn.microsoft.com/en-us/library/dd460123.aspx
Or you can set it on an individual SelectListItem via it's Selected property ( http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.selected.aspx ) and use the single-parameter constructor of the select list, or pass it straight to the DropDownList method.
Use the HTML helper ListBoxFor.
#Html.ListBoxFor(m => m.MyPropertyId, Model.MySelectList)
To build the list of items, you can use the MultiSelectList. For example, in your controller:
public ActionResult Index()
{
// Get a collection of all product id's that should be selected.
int[] productIds = _service.GetSomeProductIds();
// Make a new select list with multiple selected items.
ViewBag.List = new MultiSelectList(
_service.Products,
"Id", // Name of the value field
"Name", // Name of the display text field
productIds ); // list of selected product ids
return View();
}
Then in your view:
#Html.ListBoxFor(m => m.ProductIds, (IEnumerable<SelectListItem>)ViewBag.List)
MVC method to bind custom list to dropdownlist and select item dynamically
if you need more details ,comment below
Create Section
#{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
}
<div class="form-group">
#Html.LabelFor(model => model.SaleOrPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SaleOrPurchase, list, "-- Select Status --", new {#class= "form-control" })
#Html.ValidationMessageFor(model => model.SaleOrPurchase, "", new { #class = "text-danger" })
</div>
</div>
EDIT Section
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
IEnumerable<SelectListItem> myCollection = list.AsEnumerable();
ViewBag.SaleOrPurchase = new SelectList(myCollection, "Value", "Text", transactionTbl.SaleOrPurchase.ToString().Trim());

ASP.NET MVC DropDownListFor does not honour SelectListItem.Selected

I am using DropDownListFor to render a dropdown list in a view. Somehow the rendered list does not select the SelectListItem with Selected set to true.
In the controller action:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Selected = entry.Value.Equals(selectedValue),
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = id,
SelectList = selectList,
OptionLabel = "Click to Select"
});
In the view:
<%= Html.DropDownListFor(m => m.ListId,
Model.SelectList,
Model.OptionLabel,
new {#class="someClass"}) %>
I have tried the following:
make sure that there is one and only one items with Selected set to true.
remove the option label argument.
remove the HTML attribute object.
use SelectList in DropDownListFor:
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
Any suggestions as to what went wrong?
EDIT:
more information:
This action is a child action, called by another view with HTML.RenderAction
DropDownListFor will always select the value that the listbox is for, so in this case it will look at the value of ListId and make that item in the list selected. If ListId is not found in the list, the first item (or default text) will be selected. If you want a list that selects based on the selected attribute use DropDownList (without the For, in that case you have to name it yourself).
So in your case this would work:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
I got the same problem on the same model (with the other models in the decision no problem)
Does not work:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.Value, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Works perfectly, the elements selected:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.ToDictionary(u=>u.Value).Values, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Try like this:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
// The drop down list is bound to ListId so simply set its value
// to some element value in the list and it will get automatically
// preselected
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
and in the view:
<%= Html.DropDownListFor(
m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text"),
Model.OptionLabel,
new { #class = "someClass" }
) %>
There could be one more gotcha: you are trying to change the selected value in a POST action. For example you rendered a form, the user selected some value in the dropdown, submitted the form and in your POST action you do some processing on this selected value and when you redisplay the view you want the drop down list to have some other value selected. In this case you will have to remove the initial selection which is contained in the ModelState or the Html helper will ignore the selected value in the model:
// do this before returning the view and only if your scenario
// corresponds to what I described above
ModelState.Remove("ListId");
The solution for this problem is simpler that we all think...
All we need to do is set the property on the view model for the element that the dropdown is bound to - i.e: ListId = 3 for example
this way when we do this
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
the HtmlHelper will automatically pick up the default value to display on the DropDownList
simples!
Hope it may help you and all the others - like me! - that have lost a lot of time searching for a solution for this apparent issue.

Adding Multiple Static options to a Drop-Down in ASP.NETMVC

I want to add two default options to my dropdowns in asp.net MVC using the html helper class, they are "--Please Select--" and "--Other--".
I can add one static option using
<%= Html.DropDownList("ddlserviceGroup",
(IEnumerable<SelectListItem>)ViewData["ServiceGroups"], "--Select Item--")%>
But i need to add two options and can't seem to figure it using the HTML helper class
The existing helper doesn't allow this. I'd suggest adding the options in the controller or perhaps writing your own extension method.
var serviceGroups = db.Groups
.Select( g => new SelectListItem
{
Text = g.Name,
Value = g.ID
})
.ToList();
// prepend to list
serviceGroups.Insert( 0, new SelectListItem
{
Text = "--Select Item --",
Value = string.Empty
} );
// add at end
serviceGroups.Add( new SelectListItem
{
Text = "-- Other -- ",
Value = ????
});
ViewData["ServiceGroups"] = serviceGroups;
In View
<%=
Html.DropDownList("ddlserviceGroup",
(IEnumerable<SelectListItem>)ViewData["ServiceGroups"]
%>

Resources