MVC Application Loading Notifications - c#

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.

Related

Showing certain links based on permissions in MVC

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).

Design Patterns for C# Windows Forms

I'm writing a flashcard program and am running into an issue I always seem to face when writing this sort of Forms program.
I'll describe the program then the issue.
In this program, one main form controls almost all of the action. Depending on the user's input and form events, different buttons/controls may become enabled or disabled, text in various boxes may be populated, etc.
For example:
Some questions might be multiple choice and others require typed input.
The user inputs their answer and clicks a button -- if they get something wrong, they have the option to override the 'wrong answer' judgement and say it was really a different, correct variant.
Statistics regarding which questions were answered correctly are kept and used in the decision about what flash cards to show next.
Now the issue.
How do I best create a clean interaction between the "form" code (for example, handling the OK button's onclick command, and enabling or disabling various controls) and the "logic" code (underlying data stores, program logic that does not have immediate implications for display)? If it is all mixed together in the form object code it does not seem right.
Can anyone suggest a design pattern (especially one widely used) that manages this cleanly?
In case it is relevant I am thinking of something like this:
Object Model:
Class MyForm: the form itself.
Class FormController:
Child class of MyForm.
Instantiation requires an object of type MyForm.
FormController's job is to put its MyForm object into a particular "state," by enabling/disabling controls, displaying various text, etc.
FormController exposes a small set of public functions which deal with semantically high-level request for the form state (such as "DisplayNewQuestion(QuestionData d)")
Class Session: Contains all underlying persistent data or objects involving this session, including lists of possible questions, objects that select the next question from the list, etc.
Class Driver: Drives both the Session and FormController objects. For example, it would ask the Session object for a new question, and pass it to the FormController object to update the form.
The advantage to something like this is that icky form code and nice logic code are now completely separable. But is it worthwhile? Are there better or more common design patterns for this?
Thanks a ton!
I am always most comfortable with Model View Controller in this situation. The Shade Tree Developer wrote the most informed series I have ever read on the subject, see here
The jist of MVC is
Model contains the data to be displayed
View is your form and only has logic for displaying and informing of user interactions
Controller contains the glue to make it all happen, including the business logic.
The depenencies should be
Model doesnt know about the view or the controller
View knows about the model and knows how to extract data from it to display
Controller knows about the Model and the view, instansiates them both and wires them together.
The model raises an event when it changes, the view captures this event and refreshes its display accordingly.
The view raises an event when a user interaction occurs, the controller captures this event and performs the correct action for the interaction whether that be updating the model or saving or clearing or whatever.
The view should not write to the model itself
You will see a lot of code where the form creates the controller but imo this is wrong. It came about because of people trying to apply this pattern in asp.net webforms where you have no control over the lifecycle, the first thing that always got created was a view so you had no choice but to have this create your controller, however in winforms you are in control, so make it clean, have the controller create the view.
You might want to use the Model-View-Controller (MVC) design pattern, in which the "logic" is your controller and the "view" is your UI. The model is used to access and retrieve data from your data source (a SQL database for instance)
It is worthwhile to separate your logic from your UI, because it makes them more maintainable. For example, if you want to change your UI from a winform to a web page, you don't have to redo all your logic.
Also, it makes up for a really cleaner code. Using design patterns in general helps other programmers understand your code faster as well.

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!?

How do I limit the actions in my controller in an ASP.NET MVC application?

I writing an MVC app and I'm really struggling to keep my controllers lean and limit the number of actions.
For example, here is a look at my ReportController actions:
OpenCall
ClosedCall
ServiceLevelAgreement
Barrier
Resolution
Repair
Failure
Inventory
CustomerLocation
These are all my different reports. Should I be making a controller for each one?
Here is a look at my ServiceCallController actions:
New
Create
Reopen
UpdateETA
UpdateOnsite
UpdateServiceTimes
UpdateEnroute
Close
Cancel
Reassign
Show
ModifyAfterClose
This are all different actions I need to take based on what the user wants to do. Can anyone help me out here with how to clean this up?
I think it's clean already. If an object of yours is capable of doing 7-8 actions, then your structure is the way to go. If you had one controller that is responsible for the actions of multiple business objects, then I'd have suggested you change it into the way your current design is in.
One thing though about your current design, it'd be a good idea to just have one update action on ServiceCallController and that action could take what to update as a parameter. After all, all those update actions do one thing : update your business object.
But if you are still not satisfied, then you can just have one action that's named "do" which takes the action as parameter and passes that to a service layer which returns what the request wanted. But IMO, that wouldn't be a good design, so I definitely don't suggest it.
If the file it self is getting to large to work with you could either use partial classes, Or back the logic off in to a separate class and leave your controller think and lean.

How to apply the MVC pattern to GUI development

I am primary a web developer but I do have a very good understanding of C++ and C#. However, recently I have writing a GUI application and I have started to get lost in how to handle the relationship between my controller and view logic. In PHP it was very easy - and I could write my own MVC pattern with my eyes closed - mainly because of how PHP is stateless and you regenerate the entire form per request. But in application programming languages I get lost very quickly.
My question is: how would I separate my controller from view? Should the view attach to events from the controller - or should the view implement an interface that the controller interacts with?
If I was you I would expose events from an interface of your view. This would allow you to make the controller central to the entire interaction.
The controller would load first and instantiate the view, I would use dependency injection so that you don't create a dependency on the view itself but only on the interface.
The controller would access the model and load data into the view.
The controller would bind to events defined on the view interface.
The controller would then handle saving of data back to the model via an event.
If you wanted to you could also use an event broker which would void the need to declare an interface per view. This way you could bind to events through attributes.
This would leave you with the Controller being dependent on the model and the view interface, the view being dependent on the data only and the model having no dependencies.
Some examples of the above design thinking can be found in CAB and the Smart Client Software Factory Link To Smart Client. They use the MVP pattern but it could equally easily be applied to the MVC pattern.
Most every GUI framework (from MFC to SWT to whatever) is already MVC based. In fact, the MVC pattern was first created by Smalltalk-80 and later first really used for GUI development.
Double check and look at the standards and suggested practices for your GUI toolkit of choice. Sometimes MVC won't be a good pattern to work with when solving a certain problem or working with a particular toolkit.
Remember: MVC is a great pattern but isn't a one size fits all solution, don't try and force a problem into MVC when event-based or functional style programming will make your life easier.
Imagine this GUI:
The Zergling unit is presented to the user as an alien icon. You can see that it is in its idle animation. Call this the View.
The player moves the unit by clicking on it and a target location. You can subtitute the player for an AI if you want. Call this the Controller.
The HP and attack range of the unit is calculated every game frame when the unit is in combat. You can change this data to make the Zergling into a range unit. Call this the Model.
Keep this analogy in mind and extend it for your MVC designs.
The imortant thing for you to remember, is that in your MVC setup the Controller must know which View to call, but the View must know nothing of the Controller.
So your View must provide a generalized way for Controllers to interact with it, so that you can have several different Controllers call the same View (a standardized graphical output of some data provided as parameter, for example).
This gives you flexibility:
If your customer wants PDF output of
something you only provide HTML
output for, you can get away with
writing a new PDF View to be called
from the Controller with the same
parameters as the HTML View.
If your customer wants similar HTML output of a different data source (say), you can get away with coding a new Controller that provides a different data set to the same old HTML View, which gives the same HTML report just with other data.
If you keep your View detached from specific Controllers, and put the knowledge about which View to call from your Controller, you're well on your way.
Your controller should definately bind to events defined on an interface the view implements.
How you go about doing this can be the tricky part. Dependency injection? A view factory? Have the view instantiate the controller it wants? It really depends on how complex the application is going to be.
For something really quick and simple I would start with having each view construct it's controller and then look at other options if it needed to get bigger. Personally I think a full dependency injection framework is overkill for half a dozen forms :]

Categories

Resources