How to create dropdown list in MVC 3? - asp.net

Since i have never used a drop down list in MVC before, I am having problems creating one.
I have looked it up but i am not understanding. I want to create a basic drop down list for "Gender" in MVC3.
So far i have been able to create this.
Class:
public Dictionary<int, string> Gender {get;set; }
public StudentInformation()
{
Gender = new Dictionary<int, string>()
{
{ 0, "Male"},
{ 1, "Female"},
};
}
View:
#Html.DropDownListFor(model => model.Gender.Keys,
new SelectList(
Model.Gender,
"Key",
"Value"))
But it throws an exception "Object reference not set to an instance of the object".

Here are a bunch of different ways.
http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

Here is my solution for this,
public class Blog {
private readonly IList<Post> _list = new List<Post> {
new Post(1, "How to 1"),
new Post(2, "How to 2"),
new Post(3, "How to 3"),
new Post(4, "How to 4"),
new Post(5, "How to 5")
};
public SelectList Posts {
get {
return new SelectList(_list, "PostId", "Title");
}
}
public int? SelectedPostId { get; set; }
}
public class Post {
public Post(int postId, string title) {
PostId = postId;
Title = title;
}
public int PostId { get; set; }
public string Title { get; set; }
}
//The View:
#Html.DropDownFor(o => o.SelectedPostId, Model.Posts)
Here is the link for more of explanations:
Reference

Try This....
Controller
var value = new SelectList(new[]
{
new {ID="1",Name="ISO 9001"},
new{ID="2",Name="BIS Hallmark"},
new{ID="3",Name="ISI"},
});
ViewData["values "] = value
VIEW
#Html.DropDownList("Cert", (SelectList)ViewData["Certification"], "--Select--", new { #class="dropdownlist" ,id = "Cert" })

Related

ASP.Net Core MVC - List<SelectListItem> multiselect not showing select = true items

I'm making a strongly typed update/create view for "Medical Supplies" in which users can select multiple options ("Kits") from a dropdown list that received a List<SelectListItem>. The list is a <select multiple="multiple">. It was originally working perfectly, but I must have accidentally changed something.
Now the dropdown does not display SelectListItems passed to it as selected = true as selected (as verified by VS debugger), so I can select new items but not deselect previously selected ones. I need this to compare the list of IDs from the new selection to the old one in order to determine what must be removed from the Db.
This is my view model:
public class MedicalSupplyViewModel
{
public MedicalSupplyViewModel()
{
Supply = new MedicalSupply();
KitList = new List<SelectListItem>();
KitIds = new List<int>();
}
public MedicalSupply Supply { get; set; }
public List<SelectListItem> KitList { get; set; }
public string StringKits { get; set; }
public List<int> KitIds { get; set; }
public void KitStringSet()
{
IEnumerable<string> KitNames = Supply.KitSupplies.Select(ks => ks.Kit.Name);
StringKits = Supply.KitSupplies.Count() == 0 ? "N/A" : string.Join(", " , KitNames);
}
}
This is the relevant cshtml in my view:
<select multiple="multiple" class="form-control" id="kit_select" asp-for="KitIds" asp-items="Model.KitList"></select>
This is the part of the controller method for this page that creates the SelectListItems:
DetailsModel.KitList = _db.Kits.ToList().ConvertAll(k =>
{
return new SelectListItem()
{
Value = k.Id.ToString(),
Text = k.Name,
Selected = SelectedKits.Contains(k)
};
});
Even setting the item to selected = true will not display them as such. I've set breakpoint everywhere, including in the view, and I cannot find a discrepancy between the selected property and what it should be anywhere except for the rendered html. I've also used different browsers and spent hours searching the internet and this website.
What could be the cause of this issue?
You should set the selected items' value to the KitIds. Below is my test example:
Model:
public class MedicalSupplyViewModel
{
public MedicalSupplyViewModel()
{
KitList = new List<SelectListItem>();
KitIds = new List<int>();
}
public List<SelectListItem> KitList { get; set; }
public string StringKits { get; set; }
public List<int> KitIds { get; set; }
}
public class Kit
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller:
public IActionResult Index()
{
List<Kit> kits = new List<Kit>
{
new Kit{ Id = 1, Name = "AA"},
new Kit{ Id = 2, Name = "BB"},
new Kit{ Id = 3, Name = "CC"},
};
List<Kit> SelectedKits = new List<Kit>
{
new Kit{ Id = 1, Name = "AA"},
new Kit{ Id = 2, Name = "BB"}
};
var DetailsModel = new MedicalSupplyViewModel();
DetailsModel.KitIds = SelectedKits.Select(x => x.Id).ToList();
DetailsModel.KitList = kits.ToList().ConvertAll(k =>
{
return new SelectListItem()
{
Value = k.Id.ToString(),
Text = k.Name
};
});
return View(DetailsModel);
}
View:
<select multiple="multiple" class="form-control" id="kit_select" asp-for="KitIds" asp-items="Model.KitList"></select>
Result:

ASP.Net MVC : Binding Dropdownlist to a List on the Model [duplicate]

I'm developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.
I have this View:
#model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
The ViewModel is:
public class AggregationLevelConfViewModel
{
private readonly List<GenericIdNameType> codeTypes;
private readonly List<GenericIdNameType> helperCodeTypes;
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
public AggregationLevelConfViewModel()
{
// Load CodeTypes to show it as a DropDownList
byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
codeTypes = new List<GenericIdNameType>();
helperCodeTypes = new List<GenericIdNameType>();
for (int i = 0; i < values.Length; i++)
{
GenericIdNameType cType = new GenericIdNameType()
{
Id = values[i].ToString(),
Name = EnumHelper.GetDescription((CodeTypes)values[i])
};
if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
codeTypes.Add(cType);
helperCodeTypes.Add(cType);
}
}
}
And Models.AggregationLevelConfiguration is:
public class AggregationLevelConfiguration
{
public byte AggregationLevelConfigurationId { get; set; }
public int ProductionOrderId { get; set; }
public string Name { get; set; }
public byte CodeType { get; set; }
public byte HelperCodeType { get; set; }
public int PkgRatio { get; set; }
public int RemainingCodes { get; set; }
}
I need to set selected value in these properties:
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
But I can't set it in new SelectList(codeTypes, "Id", "Name"); or new SelectList(helperCodeTypes, "Id", "Name"); because the selected value are in Configurations array: fields AggregationLevelConfiguration.CodeType and AggregationLevelConfiguration.HelperCodeType.
I think I have to set selected value in the View, but I don't know how to do it.
How can I set the selected values?
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
The are 2 option to solve this to ensure the correct option is selected based on the model property
Option 1 (using an EditorTemplate)
Create a custom EditorTemplate for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml (note the name must match the name of the type
#model yourAssembly.AggregationLevelConfiguration
#Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
Option 2 (generate a new SelectList in each iteration and set the selectedValue)
In this option your property CodeTypeItems should to be IEnumerable<GenericIdNameType>, not a SelectList (or just make codeTypes a public property). Then in the main view
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType" - the DropDownListFor() method already generated that id attribute
I wrote this class to overcome an issue I was having with selecting an option in an html select list. I hope it helps someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Login_page.Models
{
public class HTMLSelect
{
public string id { get; set; }
public IEnumerable<string> #class { get; set; }
public string name { get; set; }
public Boolean required { get; set; }
public string size { get; set; }
public IEnumerable<SelectOption> SelectOptions { get; set; }
public HTMLSelect(IEnumerable<SelectOption> options)
{
}
public HTMLSelect(string id, string name)
{
this.id = id;
this.name = name;
}
public HTMLSelect(string id, string name, bool required, IEnumerable<SelectOption> options)
{
this.id = id;
this.name = name;
this.required = required;
}
private string BuildOpeningTag()
{
StringBuilder text = new StringBuilder();
text.Append("<select");
text.Append(this.id != null ? " id=" + '"' + this.id + '"' : "");
text.Append(this.name != null ? " name=" + '"' + this.name + '"' : "");
text.Append(">");
return text.ToString();
}
public string GenerateSelect(IEnumerable<SelectOption> options)
{
StringBuilder selectElement = new StringBuilder();
selectElement.Append(this.BuildOpeningTag());
foreach (SelectOption option in options)
{
StringBuilder text = new StringBuilder();
text.Append("\t");
text.Append("<option value=" + '"' + option.Value + '"');
text.Append(option.Selected != false ? " selected=" + '"' + "selected" + '"' + ">" : ">");
text.Append(option.Text);
text.Append("</option>");
selectElement.Append(text.ToString());
}
selectElement.Append("</select");
return selectElement.ToString();
}
}
public class SelectOption
{
public string Text { get; set; }
public Boolean Selected { get; set; }
public string Value { get; set; }
}
}
And
public IEnumerable<SelectOption> getOrderTypes()
{
List<SelectOption> orderTypes = new List<SelectOption>();
if (this.orderType == "OptionText")
{
orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
} else
{
orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
}
}
And to use it:
#{
Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
}
#Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
We had in a view this line at the top:
IEnumerable<SelectListItem> exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable<string>).Select(e => new SelectListItem() {
Value = e,
Text = e,
Selected = Model.ExitFromTrustDeed == e
});
and then below in the view:
#Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { #class = "form-control" })
We had a property in my ViewData with the same name as the selector for the lambda expression and for some reason that makes the dropdown to be rendered without any option selected.
We changed the name in ViewData to ViewData["ExitFromTrustDeed2"] and that made it work as expected.
Weird though.

Umbraco: Create CheckBoxList property with prevalues from mvc model

What I want to do is create a CheckBoxList property so the editor could choose facilities specific for current page (hotel name) in BO, and render content based on what is checked.
I've created a model:
public class Facility
{
public int Id { get; set; }
public string Description { get; set; }
public string IconUrl { get; set; }
public List<Facility> GetFacilities()
{
return new List<Facility>()
{
new Facility() { Id = 4, Description = "Free parking", IconUrl = "" },
new Facility() { Id = 6, Description = "Spa", IconUrl = "" },
new Facility() { Id = 7, Description = "Free Wifi", IconUrl = "" },
new Facility() { Id = 2, Description = "Tennis", IconUrl = "" },
new Facility() { Id = 9, Description = "Room service", IconUrl = "" },
new Facility() { Id = 10, Description = "Fitness", IconUrl = "" }
};
}
}
How can I create a CheckBoxList with the values set in GetFacilities() method? Or should I create a new class in AppCode folder with this method? Where is the best place to put this kind of functionality, and how can I achieve this?
Your Facility model should contain a boolean value to indicate if its been selected
public class FacilityVM
{
public int Id { get; set; }
public string Description { get; set; }
public bool IsSelected { get; set; }
{
public class HotelVM
{
public int ID{ get; set; }
....
public List<FacilityVM> Facilities { get; set; }
}
Controller
public ActionResult Edit(int ID)
{
HotelVM model = new HotelVM();
model.Facilities = // populate the list of available facilities
// Get the hotel from repository and map properties to the view model
return View(model);
}
public ActionResult Edit(HotelVM model)
{
...
foreach(FacilityVM facility in model.Facilities)
{
if (facility.IsSelected)
{
// do something
}
}
....
}
View
#model HotelVM
#using (Html.BeginForm())
{
// render properties of hotel
....
for (int i = 0; i < Model.Facilities.Count; i++)
{
#Html.HiddenFor(m => m.Facilities[i].ID);
#Html.HiddenFor(m => m.Facilities[i].Description);
#Html.CheckBoxFor(m => m.Facilities[i].IsSelected)
#Html.LabelFor(m => m.Facilities[i].IsSelected, Model.Facilities[i].Description)
}
<input type="submit" value="Save" />
}
I think you're thinking about this the wrong way as suggested by Stephen (unless I am misunderstanding your question). You are creating a list of key/value pairs and only one will be selected in the BO and so only one will published to the front-end (regardless of the use of it).
So, in the BO you only need a dropdown list with the key/values pairs. You can create this with the "Dropdown list (publishing keys)" datatype. Also consider using the "SQL dropdown" list datatype as this would give you far more flexibility.
If you then need to convert the selected ID into a Facility object, do this separately using a class implementing the IPropertyEditorValueConverter interface. See here for more information:
http://our.umbraco.org/documentation/extending-umbraco/Property-Editors/PropertyEditorValueConverters

Dropdown list in asp.net

i've a view. in the view i've months field(nvarchar type in database) :
#Html.DropDownListFor(model => model.rent_month,
(IEnumerable<SelectListItem>)ViewBag.months)
i've a method in a model class (PostManager) to generate months list like:
public IEnumerable<SelectListItem> GetMyMonthList()
{
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.Select(m => new SelectListItem() { Text = m, Value = m });
}
i get months in get action by :
public ActionResult Create()
{
PostModel p = new PostModel();
ViewBag.months = pm.GetMyMonthList();
return View(p);
}
in my Model my month attributes:
[Required(ErrorMessage = "You Must Select a Month.")]
[Display(Name = "Select Rent Month")]
public string rent_month { get; set; }
in the post action:
public ActionResult Create(PostModel p)
{
if (ModelState.IsValid)
{
post post = new Models.DB.post();
post.rent_month = p.rent_month;
db.posts.AddObject(post);
db.SaveChanges();
}
}
it generates month in the dropdownlist correctly.But after submit the form it gives error:
The ViewData item that has the key 'rent_month' is of type 'System.String' but must be of type 'IEnumerable'
now what is the solution for this error... thanks in advance...
I believe this is happening because in your post action you are not populating the ViewBag again. Make sure you set ViewBag.months = pm.GetMyMonthList(); in your controller POST action similar to what you have done in GET action.
Better solution would be to have a IEnumerable<SelectListItem> MonthList property as part of the PostModel. Instead of loading the months from ViewBag you can access it directly by the MonthList property
In the PostModel
public IEnumerable<SelectListItem> MonthList
{
get
{
return pm
.GetMonthList()
.Select(a => new SelectListItem
{
Value = a.Id,
Text = a.MonthText
})
.ToList();
}
}
Then in the view
#Html.DropDownListFor(model => model.rent_month, Model.MonthList)
After EDIT to the question
Your PostModel class should be like this. I have moved your GetMyMonthList() implementation out of the PostManager class.
public class PostModel
{
[Required(ErrorMessage = "You Must Select a Month.")]
[Display(Name = "Select Rent Month")]
public string rent_month { get; set; }
public IEnumerable<SelectListItem> MonthList
{
get
{
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.Select(m => new SelectListItem() { Text = m, Value = m });
}
}
}
public class PostModel
{
[Required(ErrorMessage = "You Must Select a Month.")]
[Display(Name = "Select Rent Month")]
public string rent_month { get; set; }
public IEnumerable<SelectListItem> MonthList
{
get
{
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
.Select(m => new SelectListItem() { Text = m, Value = m });
}
}
}

populate a select in ASP.net MVC3 with Data in the database using nHibernate

I need to populate the data which is in the database fields using nHibernate mapping for a select in ASP.net MVC3... Please send me a sample code of how to do it..
Regards
Srividhya
You could start by defining a view model:
public class MyViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
then a controller which will populate this view model (hardcode some values at the beginning just to make sure that it works and you have a mockup screens to show to your users):
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Items = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}
};
return View(model);
}
}
and finally a view:
#model MyViewModel
#Html.DropDownListFor(
x => x.SelectedItemId,
new SelectList(Model.Items, "Value", "Text")
)
The next step could consist into defining a model, setting the mapping for this model, a repository allowing you to fetch the model with NHibernate and finally call this repository in the controller action and map the returned model to the view model I used in the example:
Model:
public class Item
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
Repository:
public interface IItemsRepository
{
IEnumerable<Item> GetItems();
}
and now the controller becomes:
public class HomeController : Controller
{
private readonly IItemsRepository _repository;
public HomeController(IItemsRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
var items = _repository.GetItems();
var model = new MyViewModel
{
Items = items.Select(item => new SelectListItem
{
Value = item.Id.ToString(),
Text = item.Name
})
};
return View(model);
}
}
OK, we are making progress little by little. Now you can write unit tests for this controller action.
The next step would be to implement this repository:
public class ItemsRepositoryNHibernate : IItemsRepository
{
public IEnumerable<Item> GetItems()
{
throw new NotImplementedException(
"Out of the scope for this question. Checkout the NHibernate manual"
);
}
}
and the last step is to instruct your dependency injection framework to pass the correct implementation of the repository to the HomeController. For example if you use Ninject all you need to do is to write a module that will configure the kernel:
public class RepositoriesModule : StandardModule
{
public override void Load()
{
Bind<IItemsRepository>().To<ItemsRepositoryNHibernate>();
}
}

Resources