Showing certain links based on permissions in MVC - c#

The problem seems rather simple... I'm sure thousands of people have already figured this out, so maybe I'm overthinking it. How can I hide or show a link in my navigation bar based on the user's permission level? I am using custom roles (not MVCs) and storing that information in a database. The effect I want is pretty simple
_Layout.cshtml
...
#if(user.IsAdmin)
show link
...
There are several solutions to this I've found on the web and here on SO, but most seem to violate the MVC constructs.
Most of the solutions I found involved probing for data from within the view, which I'm pretty sure is bad practice. Other solutions involve utilizing the session variables from within the view to decide what is shown and what isn't. Isn't this also against best practices as views should not be able to decide on content?
The only "pure MVC" way I can think of doing this is to incorporate the value of IsAdmin into each of my view models, which seems like more hassle than it's worth. I suppose it's also possible to create a javacript solution where I use AJAX to figure out the admin status, then have it inject an html element into my navigation bar.
What is the proper way to handle this? Am I simply misunderstanding the best practices?

Maybe use a partial view within the layout? Something like this:
#Html.Partial(actionName: "NavigationLinks", controllerName: "Navigation")
That way, you can preserve the MVC conventions: the view can be stand-alone, and the navigation controller injects the model (whether from session data, or wherever).

Related

MVC Application Loading Notifications

I am going to be purchasing an MVC theme from WrapBootstrap https://wrapbootstrap.com/theme/inspinia-responsive-admin-theme-WB0R5L90S for a personal project.
There are alot of things that I like about it design wise, but it has brought up a question about the best way to load notifications in the header (really any sort of dynamic data that needs to load into the common Layout view).
I know there are a great number of ways to do this, but I am at the point in my development experience where I am trying to break my bad design habits (hacking things together so they "just work"), and look for elegant solutions where I can.
The things that make the most sense so far is to either:
1) Create a global ActionFilter that will filter all requests and throw a "LayoutViewModel" into the ViewBag, and just use the ViewBag in the _Layout view.
I'd rather do something strongly typed, but I don't see a way.
This is nice because it is available, does not require my controllers to inherit any functionality from a base class that might be cludgy, or even know that it is happening.
2) Load the page and onLoad, just do an Ajax Calls to the server to load any dynamic data I need.
This may have some disadvantages if your layout needs to change based on the data. I dislike with things snap all over the page after loading.
Is there a design pattern or MVC feature that I may be missing top accomplish this?
I may in the future I may implement something liks SignalR(or a simple timed ajax call to look for updates) to get updated data/notifications, but for now I am just looking at the initial page load.
Thank you for any ideas that you may have.
Most likely, what you're looking for is a child action. These are pretty much just like normal actions, except they'll return partial views and generally are decorated with [ChildActionOnly] to prevent routing to them via the URL bar.
[ChildActionOnly]
public ActionResult Notifications()
{
var notifications = // get the notifications;
return PartialView("_Notifications", notifications);
}
Then, in your layout, you just add the following where you want it to appear:
#Html.Action("Notifications", "Foo")
Where "Foo" is the name of the controller you put this child action in. I have a post on my blog that gives a primer on the Razor templating system that may be of use to you as well.

Separating grid view events and html to reduce reptition

I'm fairly new to ASP.NET and programming in general, and one of the problems I'm currently struggling to grasp is reducing repetitive code.
My goal is to have a master page that contains a grid view, then numerous pages can contain the grid. However, I want to be able to share code between my grids but at the same time be able to adapt unique code to each and everyone of them as some will have different attributes and data.
I've looked into separation of concerns, and other various posts/blogs but haven't found a definitive answer to how I can actually achieve what I want.
I've already tried using master pages and it worked quite well until my application continued to expand, plus I'd prefer to only use my master pages for presentation.
Could anyone provide a simple example of how I can achieve this?
Happy to provide additional information!
After spending the day doing research and testing numerous possibilities I've pretty much answered my own question.
I've setup a master page that contains the grid, the content page then retrieves the grid using accessors. This grid is then set to a property in the base class which makes it accessible where I need it to be.
edit
Event handlers were created to handle the grid events in the content pages, then those methods were overridden to allow the calls to bubble up to the base class thus allowing me to assign unique, page specific and common code where I needed it to be.

What exactly am I using?

Sorry for the vague title. I am pretty ashamed to ask this but I really need my awareness right now. I cannot identify whether I am following an MVC pattern or MVVM pattern.
In my previous internship, we had C# code (.NET) which had a controller and connected directly to the database (there wasn't a service layer). The controller would fetch information, format into JSON and give it to Angular's controller, which would display it on the view.
In my current internship, we don't use Angular. We use .cshtml files. The service layer provides its information to the controller, which formats the MODEL and gives it to the .cshtml view and which displays the content.
My questions:
Which one is MVC and which one is MVVM? Please drop down to my level and explain. Most of what I've read on the web seems to confuse me more with what I observe at work.
Everyone at work calls both of them MVC and, I am really confused now. If both are MVC, what's the difference between the two?
Angular is definitely more Model-View-ViewModel-ish. Whereas what you're doing now definitely sounds like MVC.
MVVM is a special pattern where the UI state is encapsulated in a ViewModel, so that the rendering of the final UI is fairly dumb and just data-binding. The state logic to say, show this button, or hide this area is all encapsulated in the ViewModel. One benefit, is that this allows for unit tests to be built to test the ViewModel and thereby implicitly testing all of the UI behaviors. (see: Wikipedia article on MVVM and Martin Fowler's Introduction to Presentation Model which MVVM is a variation of.)
In MVC, the view itself has the latitude to control it's behaviors, what you want to show/hide, etc based off of the data provided, the model. This means that in MVC, you can't test the UI behaviors (e.g. if something is correctly showing or hiding based on data changes) without testing the UI itself.
So in summary, MVVM, the ViewModel controls the UI behavior and the UI itself is dumb and just uses data-binding and does what it's told to do based on the logic in the ViewModel.
In MVC, the UI is 'intelligent' and re-shapes and renders itself however it feels it needs to based on the data it receives from the model.
You can basically look at how the UI is rendered and if you see the UI rendering logic making a lot of its own decisions about how to render itself based on the decision, then you pretty much know you're using MVC. If you just see a lot of data-binding, where almost every behavior is driven by a separate class that encapsulates all of the logic for showing and hiding pieces of the UI and this data is passed to the UI via data-binding, then it's probably MVVM.
I hope that helps.
In both cases, you are using MVC (or at least an MVC-ish pattern). When using the .cshtml files, you are using server-side MVC. When using Angular, you are using client-side MVC (which is probably more like MVVM). The biggest difference is where the model is rendered into HTML elements; on the client, or on the server.
In my opinion, this is a better way to view the differences in what you have done.

How to manage view management inside a asp.net mvc 3 application

I'm not sure if this is the right place for my question, but i will give it a try.
We are starting the development of a new product wich will use asp.net mvc 3 razor as the presentation layer. The application has about 7-8 different roles and all the roles have different views on wich the data will be displayed.
I've build a nice framework with the help of NHibernate and the implementation of a couple design patterns, so this side of the applicatie will be easy to adjust and apply maintenance to.
I want the presentation layer to be as adaptive as my framework and that's why i'm trying to figure out a way to have as less views as possible for all the different kind of roles but with full functionality. What kind of implementation do you use for distributing views to the end-user based on his role?
I thought about using jquery templates, but with the current possibility of views and the razor syntax it sound a bit unnecessary and not the preffered way to go.
Any information that i should keep in mind while developing this application will be nice, think about, common mistakes, best practises and suggestions etc.
Looking forward to your replies.
One way to reduce the number of views would be to use IsInRole() (or an equivalent if you have something custom) in combination with partial views. In the most simple case, you could have one view that also renders partial views within it based on specific roles. Something along the lines of:
#if (HttpContext.Current.User.IsInRole("admin")) {
#Html.Partial("_StuffForAdmins")
}
Depending of your situation, some partial views could then be shared across multiple different roles, reducing duplicate code. User interface elements that are publicly accessible by all roles could just be placed on the view itself without role checking.
EDIT: An alternative syntax is:
<div>
#if (Context.User.IsInRole("admin"))
{
#Html.Partial("_StuffForAdmins")
}
</div>

Mock MVC Site, an Outline for coders to see functionality and to start coding

I have to setup an MVC project to house all the HTML documents. This would be like a hierarchical structure using routing. The pages don’t have to function, just act as placeholders. It’s really just for the group to see all the HTML Pages to get an Idea of functionality. Then we would back fill groups of pages with the functionality by creating the controllers, model etc. How would this be best accomplished? Are there mock frameworks that could accomplish this? So it would be a project just having views, with a control ler that allows navigation between pages, simple to show mostly static HTML pages. The idea is simply for the group to see all the functionality, and to put together a structure to start coding. If possible we would like to see the correct URL based on the route table. What would be a quick solution for this while we work on the back end Object/Domain model?
This is a rather crude but simple solution. Just add the Server.Transfer line to your controller to inject the link to the physical file (I'm assuming the HTML documents exist already):
public ActionResult About()
{
//TODO: remove mock up redirect
Server.Transfer("~/MockUps/AboutUsMockUp.htm");
return View();
}
If you already have the HTML I would just go ahead and implement the views whilst you create the controllers? It may seem like a little extra work up front but by the time you work back through the above suggestion to re-implement the proper views at a later stage that could equate to more time spent!?

Categories

Resources