MVC4 Dropdown menu for Gender - asp.net-mvc-4

I am new to MVC 4, i want to create a drop downmenu for listing the gender.I tried a lot but nothing helped me, also i google it but invain.Please help me in it tha thow to create dropdown menu for gender please guide me.

<div class="editor-field">
#Html.DropDownList("Gender", new List<SelectListItem>{
new SelectListItem{ Text="Male", Value="Male"},
new SelectListItem{ Text="Female", Value="Female"}
}, "--- Select ---"
)
</div>

say we use an enum for the gender:
namespace DropdownExample.Models
{
public enum GenderType
{
Male=1,
Female=2
}
}
and we make a model like this:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace DropdownExample.Models
{
public class ActionModel
{
public ActionModel()
{
ActionsList = new List<SelectListItem>();
}
[Display(Name="Gender")]
public int ActionId { get; set; }
public IEnumerable<SelectListItem> ActionsList { get; set; }
}
}
make a controller like so:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using DropdownExample.Models;
namespace DropdownExample.Controllers
{
public class ActionController : Controller
{
public ActionResult Index()
{
ActionModel model = new ActionModel();
IEnumerable<GenderType> GenderType = Enum.GetValues(typeof(GenderType))
.Cast<GenderType>();
model.ActionsList = from action in actionTypes
select new SelectListItem
{
Text = action.ToString(),
Value = ((int)action).ToString()
};
return View(model);
}
}
}
then in your view, you use the DropDownListFor html helper you include the following:
#model DropdownExample.Models.ActionModel
#{
ViewBag.Title = "Index";
}
#Html.LabelFor(model=>model.ActionId)
#Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)
the DropDownListFor html helper uses at leats these two parameters:
the name of the property that will hold the selected value
the List<SelectListItem>() that contains all the options in the dropdownlist.

Create a Class for Gender
public class Gender
{
public int ID { get; set;}
public string Name { get; set; }
}
Create a list for Gender anywhere in the Controller
List<Gender> genderList = new List<Gender> {
new Gender{ Name="Male", ID = 1},
new Gender{ Name="Female", ID = 2}
};
You will have to create a SelectList for genders in the Action that will be passed to the view.
ViewBag.Genders= new SelectList(genderList,"ID","Name");
Finally you'll add a DropDownList to the view
#Html.DropDownList("Genders", null, htmlAttributes: new { #id = "genders", #class = "form-control" })
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })

Related

dropdownlist selection returning null # mvc4

I am trying to insert to database from view page which has dropdownlist , textbox's .. when i enter something and click on save means i am getting nothing from dropdown selection which is binded .
My code :
#model IEnumerable<iWiseapp.Models.LObmodel>
#using (#Html.BeginForm("stop", "Home", FormMethod.Post))
{
#Html.DropDownList("Data",ViewBag.Data as SelectList,"select a sdsd",new {id="LOB_ID"})
#Html.DropDownListFor("sss",new SelectList(Model,"lob_id","lob_name"))
,
#Html.DropDownList("LObmodel", new SelectList(ViewBag.data ,"Value","Text"))
#Html.DropDownListFor(model => model.lob_name, new SelectList(ViewBag.Titles,"Value","Text"))
I tried above all possibilities but nah i am confused nothing working out
ADDED MY CONTROLER CODE
[HttpGet]
public ActionResult stop()
{
ServiceReference1.Service1Client ser_obj = new ServiceReference1.Service1Client();
IEnumerable<LobList> obj = ser_obj.GetData(); //i am Getting list of data through WCF from BUSINESS LAYER WHERE i created entities via EF
List<SelectListItem> ls = new List<SelectListItem>();
foreach (var temp in obj)
{
ls.Add(new SelectListItem() { Text = temp.LOB_NAME, Value = temp.LOB_ID.ToString() });
}
//then create a view model on your controller and pass this value to it
ViewModel vm = new ViewModel();
vm.DropDown = ls; // where vm.DropDown = List<SelectListItem>();
THE COMMENTED CODE BELOW IS WHAT I AM DOING
//var mode_obj = new List<LObmodel>();
//Created LOBmodel class in model which is excat same of entities in Business class
//var jobList = new List<SelectListItem>();
//foreach (var job in obj)
//{
// var item = new SelectListItem();
// item.Value = job.LOB_ID.ToString(); //the property you want to display i.e. Title
// item.Text = job.LOB_NAME;
// jobList.Add(item);
//}
//ViewBag.Data = jobList;
return View(jobList); or return view (obj)
}
Any expert advice is appreciated
MY FIELDS , IS THESE PERFECT
public class template
{
public List<LobList> LOBs { get; set; } //LOBLIST FROM Entities in business layer
public int selectedLobId { get; set; }
public LobList SelectedLob
{
get { return LOBs.Single(u=>u.LOB_ID == selectedLobId) ;}
}
}
AND
public class LObmodel
{
public int LOB_ID { get; set; }
public string LOB_NAME { get; set; }
}
I would recommend putting the selectlist into your model instead of passing it through the view bag. The option you want is
#Html.DropDownListFor(model => model.lob_name, new SelectList(ViewBag.Titles,"Value","Text"))
you can set the selected item by setting model.lob_name on the controller and on post back that value will be set to the selected value of the dropdown
on your controller you can build the list like this
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in model){ //where model is your database
ls.Add(new SelectListItem() { Text = temp.Text, Value = temp.Value });
}
//then create a view model on your controller and pass this value to it
LObmodel vm = new LObmodel();
vm.DropDown = ls; // where vm.DropDown = List<SelectListItem>();
return View(vm);
then on your view you can reference that
#Html.DropDownListFor(x => x.lob_name, Model.DropDown)
with your model add the select list
public class LObmodel
{
public int LOB_ID { get; set; }
public string LOB_NAME { get; set; }
public List<SelectListItem> DropDown { get; set; }
}
then the top of your view would be
#model LObmodel
I had the same problem .
But i changed the view code of DDL using this code :
#Html.DropDownListFor(x => x.ClassID, (SelectList)ViewBag.ClassName);
The dropdownlist will bind to your model class called ClassID You will not be able to post the textual value of the ddl to the controller, only the ID behind the ddl.

ASP.NET MVC 4 Not populating dropdownlist from database

I am new in ASP.NET MVC 4. I want to populate dropdownlist by taking values from database. But dropdownlist doesn't populating with data. I am not getting where I am wrong. On the basis of following link I have develop my code. Is anybody have any other better way so kindly suggest. I am using code first approach with Razor engine.
Click here
My Controller class :
public class iRegController : Controller
{
private iRegDBContext l_oDbBO = new iRegDBContext();
// GET: /iReg/
public ActionResult PopulatejQgrid()
{
var BOList = l_oDbBO
.BO
.ToList()
.Select(d => new SelectListItem
{
Value = d.Id.ToString(),
Text = d.Name + "[ " + d.Code + " ]"
});
ViewBag.BOData = new SelectList(BOList, "Value", "Text");
return View();
}
}
My Model class :
public class BO
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class iRegDBContext : DbContext
{
public DbSet<BO> BO { get; set; }
}
My cshtml class :
#model MvciReg.Models.BO
#{
ViewBag.Title = "PopulatejQgrid";
}
#using (Html.BeginForm())
{
<fieldset>
BO :
#Html.DropDownList("BOData")
<p>
<input type="submit" value="Go" />
</p>
</fieldset>
}
Updated : My table name is BO and Database name is iReg. And my connectionstring is
<add name="iRegDBContext"
connectionString="Data Source=****;Initial Catalog=iReg;User ID=**;Password=****;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
Try to pass your list as a model to Html.DropDownList like this:
#Html.DropDownList("BOData", (SelectList)ViewBag.BOData)
According to msdn
#Html.DropDownList element expect a collection of type IEnumerable to populate the DropDownList. So rewriting your query such as:
IEnumerable<SelectListItem> BOList = l_oDbBO
.BO.Select(d => d)
.AsEnumerable)
.Select(d => new SelectListItem
{
Value = d.Id.ToString(),
Text = d.Name + "[ " + d.Code + " ]"
});
should do the work.
You may try another way:
public ActionResult PopulatejQgrid()
{
var myList = new List<SelectListItems>();
var list = l_oDbBO.BO.ToList();
var items = from g in list
select new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name + "[ " + g.Code + " ]"
};
foreach(var item in items)
myList.add(item);
ViewBag.BOData = myList ;
return View();
}
In you View:
#Html.DropDownList("Booo", (List<SelectListItem>)ViewBag.BOData)
public ActionResult PopulateJQgrid()
{
ViewBag.BOData = new SelectList(l_oDbBO.BO, "Name", "Name");
return View();
}
In your View:
#Html.DropDownList("BOData")
-- SelectList(Context.Table, "the ColumnName of the attribute that you used as value", "the ColumnName of the attribute that you used as the text of your dropdownlist")
:)

Drop Down List Value not passing to controller

This question should be very simple.. I am trying to pass values in my drop down list in my view to the controller.. I'm not getting errors but it's sending a null value for that property. Please help..
My code is as follows:
Controller:
public ActionResult Create()
{
var list = new []
{
new Room{ RoomID = 1, Building = "FAYARD HALL"},
new Room{ RoomID = 2, Building = "WHATEVER HALL"},
new Room{ RoomID = 3, Building = "TIME SQUARE"},
new Room{ RoomID = 4, Building = "MISSISSIPPI"},
new Room{ RoomID = 5, Building = "NEW YORK"},
};
var selectList = new SelectList(list,"RoomID", "Building");
ViewData["BuildingList"] = selectList;
return View();
}
//
// POST: /Room/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Room room)
{
if (ModelState.IsValid)
{
db.Rooms.Add(room);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(room);
}
MY VIEW:
<div>
#Html.LabelFor(model => model.Building, "Building")
</div>
<div>
#Html.DropDownList("BuildingList", String.Empty)
#Html.ValidationMessageFor(model => model.Building)
</div>
Please help...
Thank you.
Is your drop down populated? Given your code I think you need the following to do so:
#Html.DropDownListFor(model => model.Building, ViewData["BuildingList"])
ie. bind the selected value to the Building property of your Room and use the drop down list from your view model to populate the list.
I'm also not sure this is what your intention is. It seems a bit fishy that you are populating a drop down list with rooms and then based on the selection you are creating a new room.
Edit
Ok I'm going to make things a lot easier for you.
I'll start with your classes. Here is the room I am assuming you're working with:
public class Room
{
public int RoomId { get; set; }
public string Building { get; set; }
}
Now let's do something a bit better than using ViewData. I've created a view model for you. You will populate this with your select list and the item you choose in the view will be bound into the SelectedRoomId when you post the form.
public class ViewModel
{
public int SelectedRoomId { get; set; }
public SelectList RoomOptions { get; set; }
}
Controller
private SelectList GetSelectList()
{
var list = new[]
{
new Room { RoomId = 1, Building = "FAYARD HALL"},
new Room { RoomId = 2, Building = "WHATEVER HALL"},
new Room { RoomId = 3, Building = "TIME SQUARE"},
new Room { RoomId = 4, Building = "MISSISSIPPI"},
new Room { RoomId = 5, Building = "NEW YORK"}
};
return new SelectList(list, "RoomId", "Building");
}
public ActionResult Create()
{
ViewModel viewModel = new ViewModel
{
RoomOptions = GetSelectList()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(ViewModel viewModel)
{
if (ModelState.IsValid)
{
// Save here
// create a new room using the SelectedOptionId in the viewModel
return RedirectToAction("Index", "Home");
}
// repopulate the list if something failed
viewModel.RoomOptions = GetSelectList();
return View(viewModel);
}
View
#model PathToYourViewModel.ViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedRoomId, Model.RoomOptions, "-- select an option --")
<button type="submit">Submit</button>
};
Tried and tested. Good luck!
The model binding takes place with help of the names property in mvc .
In your case the name of your control is BuildingList:
#Html.DropDownList("BuildingList", (SelectList)ViewData["BuildingList"])
Therefore at your controller Action will go as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection collection)
{
var selectedValue = collection["BuildingList"];
}

DropDownListFor issue with selected values

I'm fairly new (okay well very new) to MVC. I'm trying to create a cascading dropdown list, where I can also preselect a value.
I've spent most of the day on this, but not really got very far. I've looked at a lot of resources, though the most useful were:
http://www.deliveron.com/blog/post/Creating-a-Cascading-Dropdown-in-ASPnet-MVC-3-and-jQuery.aspx - I used this heavily and got my own version of it working, I couldn't get there example working.
http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx - general oversite.
MVC DropDownList SelectedValue not displaying correctly - There is what appears to be a really good example here, following the view-model method, but for some reason it didn't seem to work for me.
What I've got so far is:
Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BLPrototype.Models
{
public class VehicleModels
{
public List<vehicle_make> getVehicleMakeList()
{
using (var db = new BLEntities())
{
List<vehicle_make> vmk = db.vehicle_make.OrderBy(r => r.vmk_name).ToList();
return vmk;
}
}
public List<vehicle_group> getVehicleModelList(string vmk_id)
{
using (var db = new BLEntities())
{
List<vehicle_group> vmo = db.vehicle_group.Where(v => v.vg_vmk_id == vmk_id).OrderBy(r => r.vg_name).ToList();
return vmo;
}
}
}
public class vmCatalogue1
{
public string Title { get; set; }
[Display(Name = "Select a make")]
public IEnumerable<SelectListItem> selectVehicleMake { get; set; }
[Display(Name = "Select a model")]
public IEnumerable<SelectListItem> selectVehicleModel { get; set; }
}
}
Controller:
using BLPrototype.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BLPrototype.Controllers
{
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
VehicleModels vm = new VehicleModels();
var model = new vmCatalogue1();
//Which is better and why?
model.selectVehicleMake = vm.getVehicleMakeList().Select(x => new SelectListItem { Value = x.vmk_id, Text = x.vmk_name });
//model.selectVehicleMake = new SelectList(vm.getVehicleMakeList(), "vmk_id", "vmk_name");
model.selectVehicleModel = new SelectList(vm.getVehicleModelList(""), "vg_id", "vg_name");
model.Title = "Title goes here";
return View(model);
}
VehicleModels vm = new VehicleModels();
[HttpPost]
public ActionResult Makes()
{
var makes = vm.getVehicleMakeList();
return Json(new SelectList(makes, "vmk_id", "vmk_name"));
}
[HttpPost]
public ActionResult Models(string vmk_id)
{
var models = vm.getVehicleModelList(vmk_id);
return Json(new SelectList(models, "vg_id", "vg_Name"));
}
}
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>#Model.Title </title>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function getModels(vmk_id) {
$.ajax({
url: "#Url.Action("Models")",
data: { vmk_id: vmk_id },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
errorHandler("error1");
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#selectVehicleModel").html(items);
}
});
}
$(document).ready(function () {
$("#selectVehicleMake").change(function () {
getModels($("#selectVehicleMake").val());
});
});
</script>
</head>
<body>
<div>
#model BLPrototype.Models.vmCatalogue1
#using (Html.BeginForm())
{
<div class="editor-label">
#Html.LabelFor(m => m.selectVehicleMake)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.selectVehicleMake, Model.selectVehicleMake, "Please select")
</div>
<div class="editor-label">
#Html.LabelFor(m => m.selectVehicleModel)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.selectVehicleModel, Model.selectVehicleModel, new { style = "width: 150px" })
</div>
}
</body>
</html>
The above example shows the cascading dropdowns. I've seen lots of different ways of populating a dropdownlistfor, I would like to do it via a View-Model. I'm really not sure which is the best way. Some examples seem to show just a list, some a list of selectlistitems and others just a selectlist. Could someone please tell me the difference and what is the 'better' way to do it... I know it often depends upon the application.
I would also like to be able to preselect a Make if I wish, I've seen some examples where you include the ID in various ways, and others by tagging it on to the end of the select list. None of them seem to work.
Also the Model shouldn't really show unless the make has been selected. Would I do this via CSS or another method?
Finally I've put the "Please Select" at the end of the make, so it shows. This doesn't seem like a great way of doing this. Could you please point me in the right direction?
Thank you for your time and I'm sorry for so many stupid noobish questions!
Thanks
Jay
A list of SelectListItems is more explicit and gives you a Selected property but it's more geared at multi-select lists and you no longer have access to the original list if your view requires it elsewhere.
Take a look at SelectList. It might work better for you in some cases. You can obtain one like this:
myList.ToSelectList("ID", "Description")
or
new SelectList(myList, "ID", "Description)
Add:
data-placeholder="Please Select"
in the same object that contains your "style = ..." if you want a placeholder until an option is selected.
I finally found the solution that I was after. I'll post it here in case anyone find this post in the future with similar errors.
Model:
public class VehicleModels
{
public List<vehicle_make> getVehicleMakeList()
{
using (var db = new BLEntities())
{
List<vehicle_make> vmk = db.vehicle_make.OrderBy(r => r.vmk_name).ToList();
return vmk;
}
}
public List<vehicle_group> getVehicleModelList(string vmk_id)
{
using (var db = new BLEntities())
{
List<vehicle_group> vmo = db.vehicle_group.Where(v => v.vg_vmk_id == vmk_id).OrderBy(r => r.vg_name).ToList();
return vmo;
}
}
}
public class vmCatalogue3
{
public string Title { get; set; }
public string selectedMakeId { get; set; }
public string SelectTopLine { get; set; }
[Display(Name = "Select a make")]
public SelectList selectVehicleMake { get; set; }
[Display(Name = "Select a model")]
public SelectList selectVehicleModel { get; set; }
}
Controller:
public ActionResult Index()
{
VehicleModels vm = new VehicleModels();
var model = new vmCatalogue3();
model.selectedMakeId = "870";
model.SelectTopLine = "Please Select";
model.selectVehicleMake = new SelectList(vm.getVehicleMakeList(), "vmk_id", "vmk_name");
model.selectVehicleModel = new SelectList(vm.getVehicleModelList(""), "vg_id", "vg_name");
return View(model);
}
View:
#Html.DropDownListFor(m => m.selectedMakeId, Model.selectVehicleMake, Model.SelectTopLine )
Hope that helps someone!

not working dropdown list in edit view in mvc4 razor

am unable to get correct value from drop down in mvc4. my edit view code is
#Html.DropDownList("IDCountry", (IEnumerable<SelectListItem>)ViewBag.IDCountry,
new { #class = "span6" })
if i use below code am able to get correct value but am unable to apply style for dropdownlist
#Html.DropDownList("IDCountry",String.empty)
please solve my problem.
You should not use the same value (IDCountry) as first and second argument for the dropdown. The first argument represents the value to bind the dropdown to while the second represents the available values. So:
#Html.DropDownList(
"SelectedCountryID",
(IEnumerable)ViewBag.IDCountry,
new { #class = "span6" }
)
To avoid all those confusions with Dropdowns I would recommend you using a view model:
public class MyViewModel
{
public string SelectedCountryID { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
and then your controller action will populate and pass this view model to the view:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
// preselected an element with Value = "2"
model.SelectedCountryID = "2";
// obviously those values could come from a database or something
model.Countries = new[]
{
new SelectListItem { Value = "1", Text = "Country 1" },
new SelectListItem { Value = "2", Text = "Country 2" },
new SelectListItem { Value = "3", Text = "Country 3" },
new SelectListItem { Value = "4", Text = "Country 4" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content("Thanks for selecting country ID: " + model.SelectedCountryID);
}
}
and finally in your view use the strongly typed helper:
#model MyViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.SelectedCountryID)
#Html.DropDownListFor(
x => x.SelectedCountryID,
Model.Countries,
new { #class = "span6" }
)
</div>
<button type="submit">OK</button>
}
See how the very instant you STOP using ViewBag and remove absolutely all traces from it in your application everything becomes crystal clear?