Passing objects to layout in mvc 5 - asp.net

I'm passing objects to the Layout from the controller like this:
public ActionResult MyProfile()
{
var roles = new List<int?>();
User.Roles.ForEach(r => roles.Add(r.ID));
return View(new ProfileModel()
{
LoginUser = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string.IsNullOrEmpty(User.LastName) ? string.Empty : User.LastName.ToLower()),
UserRole = new List<int?>(roles)
});
}
public class ModelBase {
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string LoginUser { get; set; }
public List<int?> UserRole { get; set; }
public ModelBase() {
UserRole = new List<int?>();
}
}
public class ProfileModel : ModelBase { }
This works but, I have to do this for all my Controller Action when returning a view because I need the roles and login user on all my views.
Is there a way for me to do this just once, without having to repeat it in my actions?
I try adding to it to a base controller, but ROLES and LOGINUSER were always null.
I know this has been addressed a lot on SO, but they are all doing the something.
Thanks.

Using Stephen Muecke suggestion I did this:
[ChildActionOnly]
public PartialViewResult Navigation() {
return PartialView("_Navigation", new LayoutModel(User));
}
[ChildActionOnly]
public PartialViewResult LoginInfo() {
return PartialView("_LoginInfo", new LoginInfoModel(User));
}
And
<div class="collapse navbar-collapse" id="navbar-collapse-area">
#Html.Action("LoginInfo", "Home")
</div>
<div class="col-lg-2 sidebox">
<div class="sidebar content-box" style="display: block;">
#Html.Action("Navigation", "Home")
</div>
</div>
Bernard's suggestion also works, but i prefer this.

Try this:
public ActionResult MyProfile()
{
var roles = new List<int?>();
User.Roles.ForEach(r => roles.Add(r.ID));
return View(new ProfileModel(User));
}
Model:
public class ModelBase
{
public ModelBase(User user) {
UserRole = new List<int?>();
LoginUser = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string.IsNullOrEmpty(user.LastName) ? string.Empty : user.LastName.ToLower()),
}
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string LoginUser { get; set; }
public List<int?> UserRole { get; set; }
}
ProfileModel:
public class ProfileModel : ModelBase
{
public ProfileModel(User user) : base(user) { }
}

I think it is not a bad practice to write some code in your layout. If it is a razor view or something similar you can add user name and its roles directly in the view.

Related

Populate a select list ASP.NET Core MVC

I'm busy with an ASP.NET Core MVC application, and I'm trying to populate a drop down list. I've created a view model and I have added a method to my StoresController that returns a list of stores that I want to display in a dropdown. I've been working off some online tutorials as I'm very new to asp.
View model:
public class StoreListViewModel
{
public List<StoreList> StoreList { get; set; } = new List<StoreList>();
}
public class StoreList
{
public string StoreId { get; set; } = null!;
public string StoreName { get; set; } = null!;
}
StoresController:
public IActionResult LoadStoreList()
{
if (ModelState.IsValid)
{
var storeList = new StoreListViewModel().StoreList.Select
(x => new SelectListItem { Value = x.StoreId, Text = x.StoreName }).ToList();
ViewBag.Stores = storeList;
}
return NotFound();
}
I'm trying to use ViewBag to call my LoadStoreList() method.
<select name="storeList" class="form-control" asp-items="#(new SelectList(ViewBag.Stores, "Value", "Text"))"></select>
When I load my page I get the following error
Value cannot be null. (Parameter 'items')
The page I need the dropdown list on is my CreateUser.cshtml which is bound to my UserModel and has a UsersController. The method I have created for listing the stores is in my StoresController which is bound to my StoresModel. So I'm not sure if that's causing the issue.
I've been battling with this for days, if someone could help me get this working or show me a better method, that would be great.
*Edit
The UserIndex() method is the first method that fires when my users page opens, do I call the LoadStoreList() method from there ?
UserController
public async Task<IActionResult> UsersIndex()
{
return _context.UsersView != null ?
View(await _context.UsersView.ToListAsync()) :
Problem("Entity set 'ApplicationDbContext.Users' is null.");
}
I'm trying to use ViewBag to call my LoadStoreList() method.
ViewBag cannot be used to call any method. You just need set value for ViewBag in the method which renders your show dropdownlist's page.
From your description, you said the page you need the dropdown list on is CreateUser.cshtml. Assume that you render the CreateUser.cshtml page by using CreateUser action.
CreateUser.cshtml:
<select name="storeList" class="form-control" asp-items="#(new SelectList(ViewBag.Stores, "Value", "Text"))"></select>
Controller:
public class YourController : Controller
{
private readonly YourDbcontext _context;
public YourController(YourDbcontext context)
{
_context = context;
}
[HttpGet]
public IActionResult CreateUser()
{
var storeList = _context.StoreLists.Select
(x => new SelectListItem { Value = x.StoreId , Text = x.StoreName }).ToList();
ViewBag.Stores = storeList;
return View();
}
}
YourDbcontext should be something like:
public class YourDbcontext: DbContext
{
public YourDbcontext(DbContextOptions<MvcProjContext> options)
: base(options)
{
}
public DbSet<StoreList> StoreLists{ get; set; }
}
Dont use viewbag for storing list data. Make your view page model including List, for example:
public class UserCreationViewModel{
public int Id{ get; set; }
public string Name { get; set; }
// Any other properties....
public List<StoreList> StoreList { get; set; }
}
in your controller YourController:
[HttpGet]
public IActionResult CreateUser()
{
var storeList = new StoreListViewModel().StoreList.Select
(x => new SelectListItem { Value = x.StoreId, Text = x.StoreName }).ToList();
UserCreationViewModel model=new UserCreationViewModel{
StoreList = storeList
};
return View("createUserViewName", model);
}
in createUserViewName:
#Html.DropDownList("StoreId", new SelectList(Model.StoreList, "StoreId", "StoreName"), "Select", new { #class = "form-control" })
or
<select class="form-control" asp-for="#Model.StoreId" asp-items="#(new SelectList(Model.StoreList, "StoreId", "StoreName"))">
<option value="-1">Select</option>
</select>

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DepartmentId'

There is no ViewData item of type 'IEnumerable' that has the key DepartmentId
I have already tried to show the departmentlist using the model
TestController.cs
public ActionResult Drop()
{
SampleEntities db3 = new SampleEntities();
List<tblDepartment> department = db3.tblDepartments.ToList();
ViewBag.DepartmentList = department;
return View();
}
Drop.cshtml
#model WebApplication7.Models.EmployeeViewModel
#{
ViewBag.Title = "Drop";
}
<h2>Drop</h2>
<div class="container-fluid" style="width:40%">
#Html.DropDownListFor(model=>model.DepartmentId,ViewBag.DepartmentList as
SelectList,"--Select--",new {#class="form-control" })
</div>
in your model create a new class. Try to use ViewModel
public class tblDepartmentVW
{
public int tblDepartmentid{ get; set; }
public IEnumerable<tblDepartment> tblDepartments{ get; set; }
//other data
}
In your Controller
public ActionResult Drop()
{
SampleEntities db3 = new SampleEntities();
tblDepartmentVW deptmodel= new tblDepartmentVW {
tblDepartments =db3.tblDepartments.ToList(),
//fill your properties from database
}
return View(deptmodel);
}
Check this link for more detail

How to use ViewDataDictionary with Html.Partial in asp.net core?

My case looks like this:
Model:
public class Book
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Comment
{
public string Id { get; set; }
public string BookId { get; set; }
public string Content { get; set; }
}
Controller:
public IActionResult Detail(string id)
{
ViewData["DbContext"] = _context; // DbContext
var model = ... // book model
return View(model);
}
View:
Detail view:
#if (Model?.Count > 0)
{
var context = (ApplicationDbContext)ViewData["DbContext"];
IEnumerable<Comment> comments = context.Comments.Where(x => x.BookId == Model.Id);
#Html.Partial("_Comment", comments)
}
Comment partial view:
#model IEnumerable<Comment>
#if (Model?.Count > 0)
{
<!-- display comments here... -->
}
<-- How to get "BookId" here if Model is null? -->
I've tried this:
#Html.Partial("_Comment", comments, new ViewDataDictionary { { "BookId", Model.Id } })
Then
#{
string bookid = ViewData["BookId"]?.ToString() ?? "";
}
#if (Model?.Count() > 0)
{
<!-- display comments here... -->
}
<div id="#bookid">
other implements...
</div>
But error:
'ViewDataDictionary' does not contain a constructor that takes 0
arguments
When I select ViewDataDictionary and press F12, it hits to:
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);
}
I don't know what are IModelMetadataProvider and ModelStateDictionary?
My goal: Send model comments from view Detail.cshtml to partial view _Comment.cshtml with a ViewDataDictionary which contains BookId.
My question: How can I do that?
Another way to use this is to pass the ViewData of the current view into the constructor. That way the new ViewDataDictionary gets extended with the items you put in using the collection initializer.
#Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })
Use the following code to create a ViewDataDictionary
new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) { { "BookId", Model.Id } }
On .NET Core I use ViewDataDictionary with a parameter, like:
#Html.Partial("YourPartial", new ViewDataDictionary(ViewData) { { "BookId", Model.Id } })

Displaying SQL Query Results in View

I'm new to MVC 5 with .net
Basically I'm just trying to get my bearings and I want to display some generic queries (disregard the fact that im using the master db, I just want to get the functions working right now). I'm using the authentication 2.0 which has an applicatindbcontext, but I created my own context but since I'm not really wanting to create a model (which could be the problem) I didn't know what to create for properties:
public class MasterModel : DbContext
{
public MasterModel() : base("MasterDatabaseConnection")
{ }
}
I created the controller like:
public class MasterController : Controller
{
private MasterModel db = new MasterModel();
// GET: Statistics
public ActionResult Index()
{
return View();
}
public ActionResult GetVersion()
{
string query = "SELECT ##VERSION AS Version";
IEnumerable<MasterModel> data = db.Database.SqlQuery<MasterModel>(query);
return View(data.ToList());
}
}
And finally I'm trying to figure out how to display the results in the view...and I'm completely lost (although it's possible I was lost in one of the previous steps).
#model IEnumerable<IdentitySample.Models.MasterModel>
#{
ViewBag.Title = "Index";
}
#WTF.Am.I.SupposedToPutHere
I've followed some tutorials where I've created CRUD style model view controllers, but I guess I'm not drawing the connection on how to just submit informational queries and display the results.
Create a Context:
public class MasterModel : DbContext
{
public MasterModel() : base("MasterDatabaseConnection")
{ }
public DbSet<MyModel> ModelOBJ { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ModelOBJ>().ToTable("tblModelOBJ");
}
}
Create a Model:
Public cLass MyModel
{
public int ID {get;set;}
public string Name {get;set;}
}
Public cLass MyModelRepository
{
public List<MyModel> GetALlModelFromDB()
{
MasterModel md = new MasterModel();
return md.ModelTosend.toList();
}
}
In your Controller:
public ActionResult Index()
{
return View(new MyModelRepository().GetALlModelFromDB());
}
In your View:
#model IEnumerable<IdentitySample.Models.MyModel>
#{
ViewBag.Title = "Index";
}
#foreach(var item in Model)
{
#:<div>#item.ID #item.Name </div>
}

How to bind bropdown list in Razor View (If view is not bound with any model)

Can anybody suggest me how bind a dropdown list in MVC Razor view. I am using MVC 4. I have a view that is not bound with any model class.
public class Util {
public List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
public class EmployeeType {
public int ID { get; set; }
public string Text { get; set; }
}
I have this sample code. I am new to MVC Now after this I don't know how to bind the collection returned by GetEmployeeTypes() Method to a dropdown list
Your class with method
public class Util {
public List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
Your model class with properties
public class EmployeeType {
public int ID { get; set; }
public string Text { get; set; }
}
This is sample action
public ActionResult ViewName()
{
Util xxx=new Util();
List<SelectList> SelectedItems =new List<SelectList>();
List<EmployeeType> items =xxx.GetEmpTypes();
foreach (var t in items )
{
SelectListItem s = new SelectListItem();
s.Text = t.Text;
s.Value = t.ID;
SelectedItems.Add(s);
}
ViewBag.xxxxx= SelectedItems;
return view();
}
In View
#Html.DropDownList("xxxxx", new SelectList(ViewBag.xxxxx, "Text", "Value"))
This above code just like a key, i don't tested for that code ran successfully. you can get some idea for how to bind dropdown from my code.
I had a Class like this to get all EmployeeTypes
public class Util
{
public List<EmployeeType> GetEmpTypes()
{
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
public class EmployeeType
{
public int ID { get; set; }
public string Text { get; set; }
}
In Controller I have written code to get the List of Employee Types
Util obj = new Util();
var v = obj.GetEmpTypes();
ViewBag.EmployeeTypes = v;
return View();
In the View I have written code to bind dropdown.
#Html.DropDownList("EmployeeTypes",new SelectList(ViewBag.EmployeeTypes,"ID","Text"));
Thanks #Ramesh Rajendran ( Now I understood the concept to bind dropdown)
*strong text*you should create the model selectlist like here:
public static List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
public static SelectList GetMyEmpTypes
{
get { return new SelectList(GetEmpTypes(), "ID", "Text"); }
}
then you access this method in dropdown list like
#Html.DropDownList("Name",yourProjectNameSpace.Util.GetMyEmpTypes())
when you will submit your form then it value bidden with Name get post to controller.
it is not necessary to bind with model class.you can receive the value on controller with the name that you have given in view like:
#Html.DropDownList("Name",yourProjectNameSpace.YourClass.GetEmpTypes())
Now you can recive the name value at controller like:
public ActionResult test(String Name)
{
return view();
}
and make your method static i.e GetEmpTypes() so that you can access it from view.

Resources