How to populate the retrieved values from DB in ListBox using asp.net mvc - asp.net-mvc-3

Can anyone help me how to populate the retrieved values in ListBoxFor. I tried this but doesn't works.
Code in Model:-
public List<SelectListItem> SafetyRepresentataives { get; set; }
public List<string> BusinessUnitSiteSafetyRepresentative { get; set; }
Code in Controller:=
var site = entityDB.ClientBusinessUnitSites.FirstOrDefault(m => m.ClientBusinessUnitSiteId ==
siteId);
var siteRepresentatives = from representatives in entityDB.ClientBusinessUnitSiteRepresentatives
where representatives.ClientBUSiteID == siteId
select representatives;
local.SafetyRepresentataives = (from o in entityDB.SystemUsersOrganizations.ToList()
from c in entityDB.Contact.ToList()
where o.OrganizationId == clientId && c.UserId ==
o.UserId
select new SelectListItem
{
Text = c.FirstName + "," + c.LastName,
Value = c.UserId.ToString()
}).ToList();
foreach (var representative in siteRepresentatives)
{
local.BusinessUnitSiteSafetyRepresentative.Add(representative.SafetyRepresentative.ToString());
}
Code in View:-
#Html.ListBoxFor(x => Model.BusinessUnitSiteSafetyRepresentative, new
MultiSelectList(Model.SafetyRepresentataives,"Value","Text"))
I have retrieved the values from DB as shown above. But I am unable to link these retrieved values to ListBox so as to populate them. How to do this?? Help me out please!!!!!!!!!

I think this link should help you
http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
In the sample they pass the combobox items in the viewbag.
I recomend you use a jquery plugin like autocomplete or typeahead from twitter bootstrap. So you can load asynchronously the elements.

Simply adding a default list helped me in resolving my issue. Here is the solution.
local.BusinessUnitSiteSafetyRepresentative = new List<string>();
foreach (var representative in siteRepresentatives)
{
local.BusinessUnitSiteSafetyRepresentative.Add(representative.SafetyRepresentative.ToString());
}

Related

I can't fetch data from the db with a Html.DropDownListFor, in MVC 4 (or 5)

I have read some pages regarding DDls, but I can't get my DDLF (DropDownListFor) to work. I have a model, and a db, but I don't know how I can in the view show one DDLF.
What I get to work, is this code:
#foreach (var item in Model)
{
#Html.DropDownListFor(m => item.Id,
new SelectList(ViewBag.SjukhusDropDownList),
"Choose something")
}
But then I get several DDLs. And I don't know how to insert data into them, so the data to the user will get fetched from the db. Like sending an id with something to the action, to do something with it. But here, I can only click on anything in the list, but of course, nothing will happen since I haven't bound any data to any option in that select list.
Here's an example for DropDownListFor in MVC 4
In the model create two properties, one for the list itself and one for identifying the list entries. In this example the vu-number identifies a merchant:
public class MyModel
{
[Display(Name = "VU")]
public string vu{ get; set; }
public List<SelectListItem> merchantList{ get; set; }
}
Initialize and load model data in the Http GET method of the controller:
public ActionResult ShowMerchants()
{
MyModel model = new MyModel();
model.merchantList = GetMerchants();
model.vu = model.merchantList[0].Value;
return View(model);
}
Create the list items using some rows from database. I.e. you can use TableAdapter and DataTable to achieve it:
private List<SelectListItem> GetMerchants()
{
List<SelectListItem> merchantList = new List<SelectListItem>();
MyDataSet.viewVUDataTable myDataTable = new MyDataSet.viewVUDataTable();
MyDataTableAdapters.VUListTableAdapter myTableAdapter = new MyDataTableAdapters.VUListTableAdapter();
myTableAdapter.Fill(myDataTable);
// iterate over rows in datatable
for(int i=0; i< myDataTable.Rows.Count; i++)
{
// Text is shown in the dropdownlist
// Value is used to identify the selected item
merchantList.Add(
new SelectListItem { Text = myDataTable[i].text, Value = myDataTable[i].vu});
}
return merchantList;
}
and in the view:
#Html.DropDownListFor(
model => model.vu,
Model.merchantList,
new { #class = "form-control" })

How to store join query data and retrieve using foreach loop from master layout page in asp.net mvc

I am new in asp.net mvc. I am trying to build role wise dynamic menu show in the view page. Each user can have multiple role.
I have a join query like:
My Controller looks like with join query:
var query= (from rMPageMap in db.RoleModulePageMaps
join userRole in db.UserRoleMaps
on rMPageMap.RoleId equals
join roleMaster in db.RoleMasters
on rMPageMap.RoleId equals roleMaster.Id
join modMaster in db.ModuleMaster
on rMPageMap.ModuleId equals modMaster.Id
join sModMaster in db.SubModuleMasters
on rMPageMap.SubModuleId equals sModMaster.Id
join pMaster in db.PageMasters
on rMPageMap.PageId equals pMaster.Id
where (userRole.UserId == appuser.Id &)
select new
{
rMPageMap.RoleId,
rMPageMap.PageMaster.Name,
roleMaster.Id,
roleName = roleMaster.Name,
modId = modMaster.Id,
moduleName = modMaster.Name,
subModuleId = sModMaster.Id,
subModuleName = sModMaster.Name,
pageId = pMaster.Id,
pageName = pMaster.Name,
parentPageId = pMaster.ParentPageId,
rMPageMap.AddData,
rMPageMap.EditData,
rMPageMap.ViewData,
rMPageMap.DeleteData,
rMPageMap.ShowInDashBoard,
rMPageMap.ShowInMenu
});
Session["rolemodulepage"] = query;
I find the values in the session while debugging. but i can not retrieve data from this using foreach loop in layout page.
Here is my view page that i try ro retrieve but does not work.
View Page:
#if (Request.IsAuthenticated)
{
var sessionVar = System.Web.HttpContext.Current.Session["rolemodulepage"];
foreach(var i in sessionVar) // error
{
#i.... // error
}
// So here how to retrieve data from session using foreach loop. I tried but does not work. Pls help. If you have some resource for dynamically mane show in view page pls share with me.
Can anyone explain that how to do it using showing dynamic menu by role based user in master layout page. Wihout login none can enter the site, pls explain with examples so that i can understand. Thanks in advance.
You query is generating a collection of anonymous objects which you cannot access in the view. Create a view model containing the properties you need and project your query into it, for example
public class MenuVM
{
public int RoleId { get; set; }
public string PageMasterName { get; set; }
....
}
and then modify the query to
var query = (from rMPageMap in db.RoleModulePageMaps
....
where (userRole.UserId == appuser.Id &)
select(new MenuVM()
{
RoleId = rMPageMap.RoleId,
PageMasterName = rMPageMap.PageMaster.Name,
....
}).AsEnumerable()
;
and then in the view you can cast the Session value and loop through it
var sessionVar = HttpContext.Current.Session["rolemodulepage"] as IEnumerable<MenuVM>;
if (sessionVar null)
{
foreach(var i in sessionVar)
{
....
However, as this is for generating a menu in a layout, I suggest you create move the code to a child action only method that returns a strongly typed partial view, for example in say CommonController
[ChildActionOnly]
public PartialViewResult Menu()
{
if (!Request.IsAuthenticated)
{
return null;
}
// Check if the session variable exists and if not, generate the query
// and add the result to session
return PartialView("_Menu", query);
}
and the _Menu.cshtml view would be
#model IEnumerable<MenuVM>
#foreach (var i in Model)
{
....
}
and in the layout, use
#{ Html.RenderAction("Menu", "Common"); }
to generate the html for the menu.

ASP.NET MVC 4 Want to populate dropdown list from database

I am new guy in ASP.NET MVC 4. I want to populate dropdownlist from database table BO where Column name is Id, Code, Name, OrgId. I want to bind two Code & Namecolumn's data to DataTextfield and Id column Data to DataValueField of dropdown. I have created code for this which are as follows BUT ITS NOT RETURNING DATA FROM TABLE and var BOList is remain empty :
my connectionstring is
<add name="iRegDBContext"
connectionString="Data Source=****;Initial Catalog=iReg;User ID=**;Password=****;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
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>
}
I really don't know where I am going wrong. I developed my code from reference of following link Click here . Kindly suggest correction in code ...
UPDATE: I tried following Matt Bodily's code in my controller and what I see is code is not fetching data from database and that code is
public ActionResult populatejQgrid()
{
ViewBag.BOData = GetDropDown();
return View();
}
public static List<SelectListItem> GetDropDown()
{
List<SelectListItem> ls = new List<SelectListItem>();
var lm = from m in db.BOs //fetch data from database
select m;
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.Id.ToString() });
}
return ls;
}
In Controller :
#Html.DropDownList("BOData", (List<SelectListItem>)ViewBag.BOData)
But when I saw value of ls through watch it always show me Count = 0 but its not giving me any error.
I found something new this problem. When I kept mouse pointer over var lm; it shows me query and in query table name in FROM clause is not that one in my SQL database. My SQL table name is BO and in query it is taking BOes. I don't know from where this name is coming. I think this is the main cause of all this problem So How I overcome this??
First Create a BO list for Dropdownlist in VIEW
#{
var Bolst= Model.BO.Select(cl => new SelectListItem
{
Value = cl.Value.ToString(),
Text = cl.Text== null ? String.Empty : cl.Text
});
}
#(Html.DropDownList("sampleDropdown", BOlst, "-----Select-----"))
In Controller:
return View(BOlst); // why use Viewbag when directly pass it to view
from what I see in your code you are creating the select list and setting the ViewBag.BOData on the controller.
So in order to render it on the view you should do this
#Html.DropDownList(ViewBag.BOData)
instead of
#Html.DropDownList("BOData")
Regarding the access to the database are you trying to use "code first" in an existing database?
If you are you need to override the context constructor like this
public class iRegDBContext : DbContext
{
  public iRegDBContext()
     :base("Name= iRegDBContext")
   {
   }
}
see this link http://msdn.microsoft.com/en-us/data/jj200620.aspx
Hope it helps.
try building your dropdown this way
#Html.DropDownList(x => x.Selected, PathToController.GetDropDown())
and then in your controller
public static List<SelectListItem> GetDropDown()
{
List<SelectListItem> ls = new List<SelectListItem>();
lm = (call database);
foreach (var temp in lm)
{
ls.Add(new SelectListItem() { Text = temp.name, Value = temp.id });
}
return ls;
}
Hopefully this helps
I recently had this issue also and managed to get it working using Viewbag. You will need to make it fit your Db tables but it works and is quite simple.
Populating Drop Down Box with Db Data

drop down list in mvc 3

Hey friends I am using drop down list in my mvc 3 project. Here the user choose one of the options and save it. And when he/she revisit the page than i have to make the initially saved value as selected value. Actually i am doing this with custom html helper as per need. But i am getting problem on it. I am doing this as:
else if (question_type == 7)
{
EAI.DAL.EaiEntities entities = new DAL.EaiEntities();
QuestionnaireRepository repository = new QuestionnaireRepository(entities);
SelectList typesList = repository.PopDdlList(qid);
output.Append(helper.Label(questiontext));
if (answer == "")
{
output.Append(helper.DropDownList("ddl" + question_id, typesList, "-- select type----));
}
else
{
output.Append(helper.DropDownList("ddl" + question_id, typesList, answer));
}
return helper.Raw(output.ToString());
}
Actually above code renders the selected value from database but it actually replacing the "-- select type ---" . So, After saving once if i visit the same page and save the page than i can get empty value in Formcollection.
So, please suggest the appropriate way of doing this
I usually add a few properties in my model:
int SelectedCategory { get; set; }
IEnumerable<SelectListItem> Categories { get; private set; }
and then load the data in my model constructor:
ProductService productService = new ProductService();
this.Categories =
productService.GetCategories()
.Select(c => new SelectListItem() { Text = c.Name, Id = c.Id.ToString() });
this.Categories.InsertAt(0, new SelectListItem() { Text = "--- Please Select ---", value = "" });
then in my Razor markup do something like:
#Html.DropDownListFor(m => m.SelectedCategory, Model.Categories)
This should auto wire up in the standard MVC way. Hope this helps.

MVC SelectList Drop down default

In the SelectList drop down, I like if the Count is 1, I like to default the value of what is there in the drugfamilylist which in this case is just 1 value. I cannot figure out how to do this.
I had the following below:
var drugfamilylist = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
if (drugfamilylist.Count == 1)
{
ViewBag.DrugFamily = new SelectList(drugfamilylist);
}
I tried but that idd not work either :
var drugfamilylist = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
if (drugfamilylist.Count == 1)
{
ViewBag.DrugFamily = new SelectList(drugfamilylist,drugfamilylist);
}
Typically I would have View strongly-typed to a ViewModel. The ViewModel would contain both the list of available items and the corresponding value of the currently selected element.
public class MyViewModel
{
public IList<string> DrugFamilyList;
public string SelectedDrugFamily;
}
In the controller you could then populate both the list of available items and the Selected items when the list of available items was a single element.
public ActionResult MyAction()
{
var vm = new MyViewModel();
vm.DrugFamilyList = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
vm.SelectedDrugFamily = (vm.DrugFamilyList.Count==1) ?
vm.DrugFamilyList[0] : null;
return View(vm);
}
And then use the HtmlHelper to build the select box:
#Html.DropDownListFor(m => m.SelectedDrugFamily, new SelectList(Model.DrugFamilyList, Model.SelectedDrugFamily))
However, if you didn't want to use the recommended ViewModel pattern, you could always accomplish the same thing with ViewBag.
ViewBag.DrugFamilyList = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
ViewBag.SelectedDrugFamily = (ViewBag.DrugFamilyList.Count==1) ?
ViewBag.DrugFamilyList[0] : null;
And then in the View use a similar helper:
#Html.DropDownList("desiredfieldname", new SelectList(ViewBag.DrugFamilyList, "", "", ViewBag.SelectedDrugFamily ))
This was written free-hand and not tested. I hope it helps.

Resources