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

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.

Related

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

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

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());
}

MVC3 error when passing a model from controller to view while using a viewModel

I'm sorry, for I'm sure there's a way to do this with a viewModel, however I'm very inexperienced with this and don't even know if I'm doing it correctly.
What I'm trying to do is pass multiple blogs and the profile info of the user who posted each blog to a view.
I'm getting the following error.
The model item passed into the dictionary is of type
'ACapture.Models.ViewModels.BlogViewModel', but this dictionary
requires a model item of type
'System.Collections.Generic.IEnumerable`1[ACapture.Models.ViewModels.BlogViewModel]'.
I'm trying to pass the following query results to the view.
var results = (from r in db.Blog.AsEnumerable()
join a in db.Profile on r.AccountID equals a.AccountID
select new { r, a });
return View(new BlogViewModel(results.ToList()));
}
This is my viewModel
public class BlogViewModel
{
private object p;
public BlogViewModel(object p)
{
this.p = p;
}
}
And my view
#model IEnumerable<ACapture.Models.ViewModels.BlogViewModel>
#{
ViewBag.Title = "Home Page";
}
<div class="Forum">
<p>The Forum</p>
#foreach (var item in Model)
{
<div class="ForumChild">
<img src="#item.image.img_path" alt="Not Found" />
<br />
<table>
#foreach (var comment in item.comment)
{
<tr><td></td><td>#comment.Commentation</td></tr>
}
</table>
</div>
}
</div>
Thanks in advance.
I guess you need to change your view model a little to:
public class BlogViewModel
{
public Blog Blog { get; set; }
public Profile Profile{ get; set; }
}
and then return it as follow:
var results = (from r in db.Blog.AsEnumerable()
join a in db.Profile on r.AccountID equals a.AccountID
select new new BlogViewModel { Blog = r, Profile = a });
return View(results.ToList());
Then in your foreach loop inside of view, you will get an objects that will contain both - profile and blog info, so you can use it like f.e. #item.Profile.Username
I'm not entirely sure what you're trying to accomplish with the ViewModel in this case, but it seems like you are expecting for the page to represent a single blog with a collection of comments. In this case you should replace
IEnumerable<ACapture.Models.ViewModels.BlogViewModel>
With
ACapture.Models.ViewModels.BlogViewModel
Then Model represents a single BlogViewModel, that you can iterate over the comments by using Model.comments and access the image using Model.image.img_path.
If this not the case, and you intend to have multiple BlogViewModels per page, then you will have to actually construct a collection of BlogViewModels and pass that to the view instead.

How to create a DropDownList from a LINQ query in MVC3?

I need to know how I could create a drop down list to represent all the categories in my "Categories" table.
I have already extracted the names and the values of each category I need, using this LINQ query :
var dbcontext = new LNQ2SQLDataContext();
var Q = from P in dbcontext.Categories
where P.SUB_CAT == null
select P;
I can pass this "Q" to my view like this :
In Controller :
return View(Q);
And in the View :
#model IEnumerable<MyAppName.Models.Category>
But I have no idea how to use #html.DropDownListFor() to make a darn good drop down list out of the model. :|
PLUS:
I could make a SelectList from the query "Q" like this :
var category_list = new SelectList(Q, "CAT_ID", "CAT_Name");
BUT I don't know how to create a drop down list (without using ViewBag to pass the category_list to the view) from a simple SelectList, either :|
I searched through as many blogs and websites as I could. But they didn't have the solution for my problem. I only got more and more confused!
So can anybody help please ? :/
To use DropDownListFor you'll either have to have a model that has a SelectList or data to make a selectlist out of and a property to store the selected value of the dropdown OR use the ViewBag to pass the category_list. So you can go with...
Public Class MyViewModel
{
Public Integer SelectedCategory { get; set; }
Public SelectList Categories { get; set; }
}
Public Class ItemsController : Controller
{
Public ActionResult Index()
{
var dbcontext = new LNQ2SQLDataContext();
var Q = from P in dbcontext.Categories
where P.SUB_CAT == null
select P;
var vm = new MyViewModel();
vm.Categories = new SelectList(Q, "CategoryID", "Name");
return View(vm);
}
[HttpPost()]
Public ActionResult Index(MyViewModel vm)
{
var theSelectedCategory = vm.SelectedCategory;
}
}
The view would be...
#model MyViewModel
#Html.DropDownListFor(model => model.SelectedCategory, Model.Categories, "Select Category")
Note: I don't typically code in C# so I can't guarantee the syntax is exactly right.

How can I pass any id to a linq join in [HttpGet] ActionResult for Edit

I am making a web application on MVC3, and I am using linq to communicate with the database.
I made a checkboxlist, where a user can select some options according to their choice and it gets saved in the databse table. The problem is in the Edit part.
The whole scenario is something like this:
The user can register as a restaurant owner or a Motel owner, I have assigned different Business_Type_Id as 1 and 2 for differentiating these two, I have assigned '2' for the Restaurant Business Type, and mapped the cuisines with the perticular business type in the same "Cuisines" table, by adding the "BusinessType" column into the table. the user will be assigned a Business_Id for their Business. I am providing a checkboxlist which generates its options from the database table "Cuisines" where I have given the cuisine list. From the front end the user can choose multiple cuisines according to their chioce what ever they provide in their restaurant. The choices may vary from one restaurant owner to the other, so I am storing the selected values for each and every Restaurant owner in a "BusinessCuisinesMapping" table, where I map the perticular BusinessId with the selected CuisineId by that perticular user.
Now to populate that cuisine list for edit or update I wrote a linq join, but I need to compare it with the Business_Id which is passed to the [HttpGet] ActionResult Edit. And this is point where I got stuck.
This is my linq join code which I am using in the controller:
[HttpGet]
public ActionResult Edit(int id)
{
using (var chkl = new BusinessEntities())
{
var data = (from CuisinesData in chkl.Cuisines
join BusinessCuisineMappingData in chkl.BusinessCuisineMapping
on new { CuisinesData.Id, id } equals new { BusinessCuisineMappingData.CuisinesId, BusinessCuisineMappingData.BusinessId }
where CuisinesData.BusinessTypeId == 2
select new CusinesDTO
{
Id = CuisinesData.Id,
Name = CuisinesData.Name,
IsSelected = BusinessCuisineMappingData.CuisinesId == null ? false : true
}).Distinct().ToList();
ViewBag.CuisineList = data;
}
return View();
}
This is my DTO class:
public class CusinesDTO
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
I want to comape the "id" with the "BusinessCuisineMappingData.BusinessId" field in my LINQ join, which I am getting through the [HttpGet] Actionresult Edit(int id). It prompts me an error while I try to implement it.
You cannot use a local variable in the join. However, you can use it in a Where clause. So if you do
join ...
on CuisinesData.Id equals BusinessCuisineMappingData.CuisinesId
...
where BusinessCuisineMappingData.BusinessId == id
you'll have the same effect.
"The type of the expressions in join clause is incorrect. Type inference failed in the call to 'Join'"
This suggests the types on either side of your JOIN are not equal. You are getting a compiler error; should be relatively easy to check the types on either side of your JOIN clause.
edit: rereading what you have put, I think something like the below is what you want to do:
[HttpGet]
public ActionResult Edit(int id)
{
using (var chkl = new BusinessEntities())
{
var data = (from CuisinesData in chkl.Cuisines
join BusinessCuisineMappingData in chkl.BusinessCuisineMapping
on CuisinesData.Id equals BusinessCuisineMappingData.CuisinesId
where CuisinesData.BusinessTypeId == id
select new CusinesDTO
{
Id = CuisinesData.Id,
Name = CuisinesData.Name,
IsSelected = BusinessCuisineMappingData.CuisinesId == null ? false : true
}).Distinct().ToList();
ViewBag.CuisineList = data;
}
return View();
}

Resources