ASP.NET MVC 4 Not populating dropdownlist from database - asp.net-mvc-4

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")
:)

Related

MVC Razor - How to update a multiple rows in a selected column from a dropdown list SQL

I think the title says it all...
I want to update a whole table with an input filled value into a selected column (selected from a dropdown list) if the value of another column is equal to a selected value (from another dropdown list). Putting all this together seem pretty hard for me...
Like this kind of Query...
var db = Database.Open("DatabaseX");
var updateCommand = "UPDATE TableX Set SelectedColumn(dropdownlistA) = (InputA) IF ColumnX = Selected Values(dropdownlistB)";
Sorry for my english
If you are having trouble getting the selected values from the dropdown on form submit, you may try this.
Create a view model with properties for the data for the dropdown and the selected option value.
public class CreateUserVm
{
public int SelectedCam { set; get; }
public List<SelectListItem> Cams { set; get; }
public int SelectedCat { set; get; }
public List<SelectListItem> Categories { set; get; }
}
And in your GET action, create an object of this, initialize the collection properties and send tot he view.
public ActionResult Create()
{
var v = new CreateUserVm
{
Categories = new List<SelectListItem>
{
new SelectListItem {Value = "1", Text = "Photo"},
new SelectListItem {Value = "2", Text = "Video"}
},
Cams = new List<SelectListItem>
{
new SelectListItem {Value = "25", Text = "DSLR"},
new SelectListItem {Value = "28", Text = "Point and Shoot"}
}
};
return View(v);
}
Now your create view should be strongly typed to this CreateUserVm class.
#model CreateUserVm
#using(Html.BeginForm())
{
#Html.DropDownListFor(g=>g.SelectedCat, Model.Categories)
#Html.DropDownListFor(g=>g.SelectedCam, Model.Cams)
<input type="submit" />
}
And in your HttpPost action method, we will use the CreateUserVm object as the parameter so that the posted model will be mapped to it by the default model binder.
[HttpPost]
public ActionResult Create(CreateUserVm model)
{
var camId = model.SelectedCam;
var catId = model.SelectedCat;
// use camId and catId to update your db.
// to do : Save and Redirect
}

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.

MVC4 Dropdown menu for Gender

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" })

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"];
}

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?