Dropdown list in MVC view - asp.net-mvc

I'm trying to create a dropdown list and I get nothing in the dropdown except 'Please select one' but no values.
I've tried this so far:
View:
<select asp-for="StatusToEdit.Color.Name" asp-items="Model.AvailableColors">
<option>Please select one</option>
</select>
Model:
public SelectList AvailableColors { get; set; }
public void OnGet()
{
AvailableColors = new SelectList(nameof(StatusColor.ColorId),
nameof(StatusColor.Name));
}
Mocklist:
private static List<ItemStatus> _mockStatuses = new List<ItemStatus>
{
new ItemStatus { StatusId = 1, Name = "Complete", Color = new
StatusColor{ ColorId = 1, Name = "Auto" } },
new ItemStatus { StatusId = 2, Name = "Complete, Ongoing", Color =
new StatusColor{ ColorId = 2, Name = "Green" }},
new ItemStatus { StatusId = 3, Name = "In Process", Color = new
StatusColor{ ColorId = 3, Name = "Yellow" }}
};
I expect to see all of the colors to show in the dropdown.

if you are using asp.net core MVC (Razor Pages is similar), you need to modify the model property type to IEnumerable<SelectListItem> AvailableColors or List<SelectListItem> AvailableColors
1.Model
public class ManageStatusesEditViewModel
{
//other properties
public List<SelectListItem> AvailableColors { get; set; }
}
2.Action:
[HttpGet]
public IActionResult ManageStatusesEdit(int id)
{
//other logic
var dropdownData = new List<SelectListItem>();
_mockStatuses.ForEach(d => dropdownData.Add(new SelectListItem()
{
Value = d.Color.Name,
Text = d.Color.Name
}));
var editManageStatusesEditViewModel = new ManageStatusesEditViewModel
{
AvailableColors = dropdownData
};
return View(editManageStatusesEditViewModel);
}
3.View:
<select asp-for="StatusToEdit.Color.Name" asp-items="Model.AvailableColors">
<option>Please select one</option>
</select>
4.Result:

You should create your list as below:
ViewBag.ColorList = new SelectList(_mockStatuses.Select(d=> { return new SelectListItem { Text = d.Color.Name, Value = d.Color.ColorId.ToString() }; }),"Value","Text");
I used ViewBag for it but you can obviously pass it to your view by a ViewModel if you prefer.
For your View you should do something as below:
<select asp-items="#ViewBag.ColorList" asp-for="StatusToEdit.Color.Name" >
<option value="">Please select one</option>
</select>
Please make sure you have added Value and Text at the end of SelectList when creating it.

Related

Client side validation doesn't work for the dropdown

View
#Html.DropDownListFor(m => m.InsertCustomer.CountryID, Model.lstCountry, new { #class = "DropDownListFor" })
#Html.ValidationMessageFor(m =>m.InsertCustomer.CountryID)
View Model
[Required(ErrorMessage = "Please Select Country")]
public string CountryID { get; set; }
Method to create a list for the dropdown
public IEnumerable<SelectListItem> getCountry()
{
DNC_DAL.clsCustomerMaster _objDalUser = new DNC_DAL.clsCustomerMaster();
DataTable dtCountry = new DataTable();
dtCountry = _objDalUser.GetCountry();
List<SelectListItem> lstCountry = new List<SelectListItem>();
SelectListItem firstOption = new SelectListItem() { Text = "---Select One---" };
lstCountry.Add(firstOption);
foreach (DataRow drCountry in dtCountry.Rows)
{
SelectListItem Country = new SelectListItem() { Text = drCountry["DCM_DESC"].ToString(), Value = drCountry["DCM_ID"].ToString() };
lstCountry.Add(Country);
}
return lstCountry;
}
Controller
public ActionResult wfrmCustomerMaster()
{
Models.clsCustomerMaster CustomerModel = new Models.clsCustomerMaster();
IEnumerable<SelectListItem> strCountry = null;
strCountry = CustomerModel.getCountry();
CustomerModel.lstCountry = strCountry;
return View(CustomerModel);
}
All the other validations( Not posted in the question) work perfectly on the page except for the dropdown validation, I wonder why?
Your code is adding the first option as
<option>---Select One---</option>
which does not have a value="" attribute, which means if you select it, the value of the <select> element will be "---Select One---", which is valid (i.e. its not null or an empty string).
Instead, to generate a label option with a null value, use the overload that accepts a optionLabel, which will generate the first option as
<option value="">---Select One---</option>
and remove the code in the getCountry() which generates this option

Passing Model data from View to Controller

I am trying to pass the Model data from a View (and PartialView within the View) back to the Controller upon HttpPost. (Adapted from Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3)
Why? I want to show a list of assets each with a DropDownList and number of options. Upon submission of form to read the selected items from DropDownList.
My 2 (simplified) models:
public class Booking
{
public int BookingID { get; set; }
public int StoreID { get; set; }
...
public IEnumerable<AssetShort> Assets { get; set; }
}
and
public class AssetShort
{
public int AssetID { get; set; }
....
public int SelectedAction { get; set; }
public IEnumerable<SelectListItem> ActionList { get; set; }
}
In my Booking Controller > Create I build the List:
public ActionResult Booking(int id)
{
// get myBag which contains a List<Asset>
// booking corresponds to 'id'
var myAssets = new List<AssetShort>();
foreach (var a in myBag.Assets)
{
var b = new AssetShort();
b.AssetID = a.ID;
b.SelectedAction = 0;
b.ActionList = new[]
{
new SelectListItem { Selected = true, Value = "0", Text = "Select..."},
new SelectListItem { Selected = false, Value = "1", Text = "Add"},
new SelectListItem { Selected = false, Value = "2", Text = "Remove"},
new SelectListItem { Selected = false, Value = "3", Text = "Relocate"},
new SelectListItem { Selected = false, Value = "4", Text = "Upgrade"},
new SelectListItem { Selected = false, Value = "5", Text = "Downgrade"}
};
myAssets.Add(b);
};
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myAssets.ToList(),
};
return View(model);
My View:
#model uatlab.ViewModels.BookingRequirementsViewModel
#{
ViewBag.Title = "Booking step 2";
}
<h4>Your booking ref. #Model.BookingID</h4>
#using (Html.BeginForm("Booking2", "Booking", FormMethod.Post))
{
<fieldset>
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.StoreID)
#Html.Partial("_Assets", Model.StoreAssets)
<input type="submit" value="Cancel" class="btn btn-default" />
<input type="submit" value="Next" class="btn btn-default" />
</fieldset>
}
The Partial View includes
#foreach (var item in Model)
{
<tr>
<td>#item.Name</td>
<td>#item.Number</td>
<td>#Html.DropDownListFor(modelItem=>item.SelectedAction, item.ActionList)</td>
</tr>
}
So, all this works fine in the browser and I can select dropdowns for each asset listed but when I submit the only value posted back is the StoreID as it is in a "HiddenFor".
The booking2 controller has the model for a parameter:
public ActionResult Booking2(BookingRequirementsViewModel model)
{
//loop through model.Assets and display SelectedActions
}
Let me make it clear what the problems is - in Booking2 controller the Model is null when viewed in Debug mode and I get error "Object reference not set to an instance of an object."
Any ideas please how to pass back the Model to controller from view?
Regards
Craig
You need to create an EditorTemplate for AssetShort. I also suggest moving ActionList to the BookingRequirementsViewModel so your not regenerating a new SelectList for each AssetShort
The models you have posted aren't making sense. Your controller has var model = new BookingRequirementsViewModel { ..., Assets = myAssets.ToList() }; but in the view you refer to #Html.Partial("_Assets", Model.StoreAssets)? Are these 2 different properties. I will assume that StoreAssets is IEnumerable<AssetShort>
/Views/Shared/EditorTemplates/AssetShort.cshtml
#model AssetShort
<tr>
<td>#Html.DispayFor(m => m.Name)</td>
....
<td>
#Html.DropDownListFor(m => m.SelectedAction, (IEnumerable<SelectListItem>)ViewData["actionList"], "--Please select--")
#Html.ValidationMessageFor(m => m.SelectedAction)
</td>
</tr>
In the main view
#model uatlab.ViewModels.BookingRequirementsViewModel
....
#using (Html.BeginForm()) // Not sure why you post to a method with a different name
{
....
#Html.HiddenFor(m => m.StoreID)
#Html.EditorFor(m => m.StoreAssets, new { actionList = Model.ActionList })
....
}
In the controller
public ActionResult Booking(int id)
{
....
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myBag.Assets.Select(a => new AssetShort()
{
AssetID = a.ID,
SelectedAction = a.SelectedAction, // assign this if you want a selected option, otherwise the "--Please select--" option will be selected
....
})
};
ConfigureViewModel(model); // Assign select list
return View(model);
}
And a separate method to generate the SelectList because it needs to be called in the GET method and again in the POST method if you return the view. Note use the overload of DropDownListFor() to generate the option label (null value) as above, and there is no point setting the Selected property (the value of SelectedAction determines what is selected, not this)
private ConfigureViewModel(BookingRequirementsViewModel model)
{
model.ActionList = new[]
{
new SelectListItem { Value = "1", Text = "Add"},
....
new SelectListItem { Value = "5", Text = "Downgrade"}
};
}
and the POST
public ActionResult Booking(BookingRequirementsViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // Re-assign select list
return View(model);
}
// save and redirect
}
I recommend also making SelectedAction nullable with the [Required] attribute so you get client and server side validation
public class AssetShort
{
public int AssetID { get; set; }
....
[Required]
public int? SelectedAction { get; set; }
}

how to get data from static dropdown list to model in mvc4

I have one static dropdown list in my view
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
I want to bind this drop down list with my model so that when I submit selected value of drop down , I get that value from model in my controller.
Also I want to select option in drop down as per data in my model.
I just made list item for static dropdown list & passed it to dropdown list where I binded it with my viewmodel.
#{
var listItems = new List<ListItem> {new ListItem {Text = "Single", Value = "Single"}, new ListItem {Text = "Married", Value = "Married"}, new ListItem {Text = "Divorse", Value = "Divorse"}};
}
#Html.DropDownListFor(model => model.EmployeeDetail.MaritalStatus, new SelectList(listItems),"-- Select Status --")
It works perfectly for me as it shows value which comes from model & also stores value of dropdown list in model when I submit data.
Instead of constructing the drop down list in HTML, build it in your service/controller and add it to your model:
ViewModel:
public class YourViewModel
{
public string SelectedCarManufacturer { get; set; }
public Dictionary<string, string> CarManufaturers { get; set; }
// your other model properties
}
Controller get action method
[HttpGet]
public ActionResult SomeAction()
{
var model = new YourViewModel
{
SelectedCarManufacturer = null, // you could get this value from your repository if you need an initial value
CarManufaturers = new Dictionary<string, string>
{
{ "volvo", "Volvo" },
{ "saab", "Saab" },
{ "audi", "Audi" },
/// etc.
}
};
return this.View(model);
}
In your view, replace the hard coded drop down list with:
#Html.DropDownListFor(m => m.SelectedCarManufacturer , new SelectList(Model.CarManufaturers , "Key", "Value"), "Select a manufacturer...")
Controller post action method
[HttpPost]
public ActionResult SomeSaveAction(YourViewModel model)
{
// do something with the model...
// model.SelectedCarManufacturer
}
OR
[HttpPost]
public ActionResult SomeSaveAction()
{
var model = someService.BuildYourViewModel()
this.TryUpdateModel(model);
// do something with the model...
someService.SaveYourViewModel(model);
}
I hope this helps...
in controller
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Volvo", Value = "volvo"});
items.Add(new SelectListItem { Text = "Saab", Value = "saab" });
items.Add(new SelectListItem { Text = "Mercedes", Value = "mercedes" });
items.Add(new SelectListItem { Text = "Audi", Value = "audi" });
on view
Html.DropDownListFor(Model.items)

ASP .Net MVC 3 Html.DropDown not binding to variable

I have a list of Organizations (CalledOrganizationSelectList) and one of them is the one that's being called (CalledOrganizationId). I set both in my ViewModel but MVC / Razor doesn't render the dropdown correctly (ie does not set the selected="selected" attribute for the correct item in the dropdown).
There is a workaround which makes even less sense. I added a new member to my ViewModel and bound the dropdown to that. This works fine. Until just now when it's stopped working...
public class CallViewModel{
public int? CalledOrganizationId { get; set; }
public SelectList CalledOrganizationSelectList { get; set; }}
In my controller:
var vm = new CallViewModel();
var calledOrganizationSelectList = new List<object>();
calledOrganizationSelectList.Add( new {Text="",Id=""});
calledOrganizationSelectList.AddRange(
db.MyOrganizations.OrderBy(x=>x.Name)
.Select(x => new { Text = x.Name, Id = x.Id.ToString()}).ToList());
var sl = new SelectList(calledOrganizationSelectList, "Id", "Text",
vm.CalledOrganizationId);
vm.CalledOrganizationSelectList = sl;
return View(vm);
In my view:
<div>CalledOrganizationId = #Model.CalledOrganizationId :
select list contains
<ul>#foreach (var itm in Model.CalledOrganizationSelectList)
{<li>Value: #itm.Value Text: #itm.Text Is Selected: #itm.Selected</li>}
</ul>
</div>
#Html.DropDownList("CalledOrganizationId", Model.CalledOrganizationSelectList)
In my rendered page source:
<div>CalledOrganizationId = 38 : select list contains
<ul>
<li>Value: Text: Is Selected: False</li>
<li>Value: 37 Text: rrr Is Selected: False</li>
<li>Value: 38 Text: sss1 Is Selected: True</li>
</ul>
</div>
<select data-val="true" data-val-number="The field CalledOrganizationId must be a number." id="CalledOrganizationId" name="CalledOrganizationId">
<option selected="selected" value=""></option>
<option value="37">rrr</option>
<option value="38">sss1</option> </select>
I've worked around it after first pulling out what was left of my hair and then by introducing a new variable on my ViewModel, which seems to work ok.
Having 2 properties on your viewmodel is the correct way to do DropDownLists. One property holds all of the available options, and the other holds the currently selected option:
public class CallViewModel
{
// this captures the selected item
public int? CalledOrganizationId { get; set; }
// this contains the select list options
public IEnumerable<SelectListItem> CalledOrganizationSelectList { get; set; }
}
However, you do not need to add the empty option in the controller. You can do this in the view:
#Html.DropDownListFor(m => m.CalledOrganizationId,
Model.CalledOrganizationSelectList, "")
You can just get away with this in the controller:
var vm = new CallViewModel();
//var calledOrganizationSelectList = new List<object>();
//calledOrganizationSelectList.Add( new {Text="",Id=""});
//calledOrganizationSelectList.AddRange(
//db.MyOrganizations.OrderBy(x=>x.Name)
// .Select(x => new { Text = x.Name, Id = x.Id.ToString()}).ToList());
//var sl = new SelectList(calledOrganizationSelectList, "Id", "Text",
// vm.CalledOrganizationId);
//vm.CalledOrganizationSelectList = sl;
vm.CalledOrganizationSelectList = db.MyOrganizations.OrderBy(x => x.Name)
.Select(x => new SelectListItem
{
Text = x.Name,
//Id = x.Id.ToString() // do not use "Id" for the property name,
Value = x.Id.ToString() // use "Value" -- it is a SelectListItem property
});
// if you want to set the selected item on the dropdownlist, do it here
vm.CalledOrganizationId = 37;
return View(vm);

How to show multiple selected with asp.net mvc 3 and ListBoxFor?

I have this VM properties
public IList<Guid> SelectedEligiableCategories { get; set; }
public IList<SelectListItem> EligiableCategories { get; set; }
I have this helpers in my view
#Html.LabelFor(x => x.EligibleCategoryFrmVm.SelectedEligiableCategories, "Eligible Categories:")
#Html.ListBoxFor(x => Model.EligibleCategoryFrmVm.SelectedEligiableCategories, Model.EligibleCategoryFrmVm.EligiableCategories, new { #class = "eligibleCategoryListBox" })
I have this code in my controller
List<SelectListItem> eligibleCategoriesListItems = Mapper.Map<List<EligibleCategory>, List<SelectListItem>>(eligibleCategories);
foreach (var rewardTier in creditCard.RewardTiers)
{
CbRewardTierFrmVm rewardTierFrmVm = new CbRewardTierFrmVm();
rewardTierFrmVm.EligibleCategoryFrmVm.EligiableCategories = eligibleCategoriesListItems;
foreach (var ec in rewardTier.EligibleCategories)
{
rewardTierFrmVm.EligibleCategoryFrmVm.SelectedEligiableCategories.Add(ec.Id);
}
vm.CbRewardTierFrmVm.Add(rewardTierFrmVm);
}
Yet when I load up my view. None of values for my ListBox are selected. I am not sure why. If this was a selectList this would work as it would match up the SelectedEligiableCategories to the value in the list.
I am not sure if this is because there is multiple selects
Edit
<select name="CbRewardTierFrmVm[63b504c0-0f9a-47ba-a8ff-db85f48d5f0f].EligibleCategoryFrmVm.SelectedEligiableCategories" multiple="multiple" id="CbRewardTierFrmVm_63b504c0-0f9a-47ba-a8ff-db85f48d5f0f__EligibleCategoryFrmVm_SelectedEligiableCategories" data-val-required="Must choose at least one eligible category." data-val="true" class="eligibleCategoryListBox ui-wizard-content ui-helper-reset ui-state-default" style="display: none;">
<option value="ed2bb5f9-4565-4f69-ab15-9fca011c0692">Gas</option>
</select>
Do you think it is because I am using http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ ?
Edit2
I gone ahead and make an example. I must be missing something(not sure what). When I use "Darin Dimitrov" it works.
I switched the example to a dropdown as I am getting the same problem with it as well.
In this example I am not using a viewmodel since my initial assumption was somehow the helper I was using from Steven Sanders might be effecting it so I was going off his example.
This does not seem to be the case as I removed it and still get this problem.
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
public string SelectedItem { get; set; }
public IList<SelectListItem> Items { get; set; }
}
public ActionResult Index()
{
List<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem {Value = "",Text ="--"},
new SelectListItem {Value = "1",Text ="1"},
new SelectListItem {Value = "2",Text ="2"},
};
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95, Items = items, SelectedItem = "2" },
new Gift { Name = "Long Cloak", Price = 120.00, Items = items, SelectedItem = "1" }
};
return View("Index3",initialData);
}
#model IList<EditorDemo.Models.Gift>
#{
ViewBag.Title = "Index3";
}
#for (int i = 0; i < Model.Count; i++)
{
#Html.DropDownListFor(x => x[i].SelectedItem, new SelectList(Model[i].Items, "Value", "Text"))
}
It seems to not be able to handle when you put it in forloop and try it make more than one dropdown list.
The following works for me.
Model:
public class MyViewModel
{
public IList<Guid> SelectedEligiableCategories { get; set; }
public IList<SelectListItem> EligiableCategories { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
SelectedEligiableCategories = new[]
{
// preselect the second and the fourth item
new Guid("35830042-3556-11E1-BCDC-A6184924019B"),
new Guid("4253876A-3556-11E1-BC17-B7184924019B")
}.ToList(),
EligiableCategories = new[]
{
new SelectListItem { Value = "2DA62E3A-3556-11E1-8A0A-9B184924019B", Text = "item 1" },
new SelectListItem { Value = "35830042-3556-11E1-BCDC-A6184924019B", Text = "item 2" },
new SelectListItem { Value = "3D07EBAC-3556-11E1-8943-B6184924019B", Text = "item 3" },
new SelectListItem { Value = "4253876A-3556-11E1-BC17-B7184924019B", Text = "item 4" },
}
};
return View(model);
}
}
View:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.ListBoxFor(
x => x.SelectedEligiableCategories,
Model.EligiableCategories,
new { #class = "eligibleCategoryListBox" }
)
}
Result:
UPDATE:
Now that you have shown an example allowing to illustrate the problem, you could specify the selected item when building the SelectList:
#Html.DropDownListFor(
x => x[i].SelectedItem,
new SelectList(Model[i].Items, "Value", "Text", Model[i].SelectedItem)
)
The reason a value was not preselected was because you were binding the dropdownlist to a list of properties (x => x[i].SelectedItem) whereas in my example I was using a simple property.
And if you wanted to do this with the ListBoxFor helper you could use the following:
#Html.ListBoxFor(
x => x[i].SelectedItems,
new MultiSelectList(Model[i].Items, "Value", "Text", Model[i].SelectedItems)
)
The SelectedItems property becomes a collection and we use a MultiSelectList instead of a SelectList.
The main problem is using
#Html.DropDownListFor
instead of this
#Html.ListBoxFor
Using the DropDownListFor will NOT help you with multiple values, whatever you do and no matter what your model is. Once you use ListBoxFor ... it will automatically just work !

Resources