Generic controller in MVC - c#

Can you explain to me the point of a controller when all it does it return a view? Have I missed the point here?
I've come across a situation when trying to build a rudimentary CMS where the user can create views (stored in the database), but of course as they are user created, the controller's don't exist. So is there another way to serve them?
Thanks for any help, I'm still trying to get to grips with MVC fully!

Can you explain to me the point of a controller when all it does it return a view?
Who said that all a controller does is to return a view? A controller does lots of other things. For example it could receive the user input under the form of an action parameters, check whether the ModelState.IsValid, do some processing on the Model and then return a View which is the whole point of the MVC pattern.
I've come across a situation when trying to build a rudimentary CMS
where the user can create views (stored in the database), but of
course as they are user created, the controller's don't exist. So is
there another way to serve them?
Yes, of course. You could use a custom virtual path provider by implementing the VirtualPathProvider class.

Related

How to use partial views in asp.net razor-pages properly?

I'm currently working on asp.net core mvc project. There is a main page (cshtml), which contains some data and two partial views in it.
Controller of this page contains action, which returns model to the view (With model binding). I've guessed that 2 more actions in the controller created to return data to both partial views would work just fine. But now my application is not working, because it is trying to pass data from main page to the partial views, creating a binding error (Partial views both has their unique models).
I'm currently using <partial> tag to add my partial views to the main view. This tag contains a property view-data which would resolve the problem with model binding. But it feels like creating a big union object with a lot of sub-objects to pass it through view-data wont be a good practice.
So i'd like to have an opinions on best practices with handling this kind of cases. What is the best way to create pages with multiple separated data like this?
My current opinion is that the best way is to make main view get viable information from the controller and in partial views make it through ajax. But anyway, there is still a question how to bypass this error with the application trying to pass data from main view to partial view (Like if i want to keep model binding in partial view to fill it with ajax).
So after some research i came to the conclusion and found a solution for my problem. PartialViews is not made for such cases. PartialView always depends on model information coming from its parent View.
Instead, if you want to achieve the same kind of behavior as i do you should use ViewComponents. It is completely independent tool which has an ability to make its own data access and build whatever model it needs. You also can access ViewComponent anywhere in your views even layouts, and even pass parameters to it by name.
I hope anyone finds this article helpful. Here is official guide by msdn on how to implement and use view components

ASP.NET MVC UML class diagram design

This is my first attempt in creating an MVC program and my first month using ASP.NET.
So far I understand the basic from MVC framework. The software that I am trying to create is an online application, basically a survey in which the admin is able to modify the questions and members with a login are able to see the results from the survey.
I am currently stuck trying to figure out how my class diagram will look like.
So far the Model interacts with the database and contains the following classes
DAOSurvey (get and setter for the data)
SurveyModel (Execute all the queries)
SurveyQueries (Add and retrieve the results from the survey)
ISurvey (Interface to communicate with controller)
Now, I know that I need some view classes, it is correct to have a "Loginview" "Adminview" "Membersview" and "Surveyview" ? I should create a class for every asp page in my ASP.NET application?
Finally I need the controller classes, which I am guessing that Admin and Members should be.
I am quite sure about the model side of my class diagram should look like, however, I am lost about how view classes and controller classes should be. Any suggestions?.
Thanks in advance.
In ASP.NET MVC you will get features like Login and register automatically if you change the authentication to Individual user account while creating a new project or you can manually change it if you have already created the project.
Here you can create logins for different user roles and then use role based authorization for different controllers.

MVC explanation and usuage

We are currently learning how to use c# at university, and we have been given a project that uses mvc, I would like to know what mvc is all about and how do we implement it? Any suggestions will be appreciated
No short sweet answer here will give it full justice, please have a look at this article.
wiki Model View Controller
or maybe even this
https://softwareengineering.stackexchange.com/questions/127624/what-is-mvc-really
As for the implementation of the pattern it will depend entirely on what your using to program with. I would advise search for mvc in the language or technology of your choice and follow a few examples, then get started once you understand the concepts of MVC
Have a look at this article from CodeProject.
It explains the MVC using a simple C# WinForms application.
http://www.codeproject.com/Articles/383153/The-Model-View-Controller-MVC-Pattern-with-Csharp
This is the best site to go. http://www.asp.net/mvc
For me if you want full control and testable web app without having to worry on the UI, I would use MVC. Everyone is going to this route. And so am I. =)
MVC firstly stands for Model View Controller.
Controllers
Controllers are nothing but classes which inherit from Controller base class and have different functions.
For example:
public class SchoolController : Controller
{
public SomeReturnType AllStudents
{
// Return all students
}
// More Functions here...
}
And these functions are responsible for providing response to the client request. When a client tries to open a URL (www.example.com/School/AllStudents) -
MVC does mapping to Controller Class SchoolController and then to the method AllStudents
Models
Now models are again classes. Models represent your database tables. So for example, if you have a student table in SQL then we will have Student Model in MVC. Example:
public Class Student
{
public int StudentId{get;set;}
public string Name {get;set;}
public DateTime DOB{get;set;}
}
Now in order to bring data from the database and put into our model, we use EntityFramework. So entity framework connects to the database and puts the data from the database table into our model.
Views
Now understand as I said earlier controller action will get called on client request. Now It is the duty of controller action(function) to provide response to the client requests. Now When the client requests for School/AllStudents, I can return it a simple list of strings, and it will get displayed on browser in the raw form. i.e. No formatting just the plain data. Now obviously we would not do that, instead I will make a good HTML page with the List of students and then send to the client.
So here comes Views in the picture. Views are simply HTML templates. In which you fill your data and return to the client.
In my mind I think of MVC as a routing mechanism.
To proceed further on learning MVC i would advise you to brush up your basic concepts on:
LINQ
Lambda Functions
Extension methods
Anonymous Types
These concepts are used everywhere in MVC.
Good Luck!

Should I inject services into my MVC views?

We're working on some kind of Cloud CMS using ASP.NET MVC technology, and have found some obstacles on the way. There is a number of parameters user could change thru the control panel that we need to end up in Views. For example, Facebook application id to initialize the Facebook JS API. Or additional text to be shown on the page. Or background picture. For now we're not using DI to transfer this parameters, instead we're adding them to the ViewModel, but this ruin the ASP.NET MVC way of working with models (e.g. form validation, bindings etc.)
It looks like that using DI to inject services for providing parameters, texts and pictures could make my views less dependent on controllers specific, and there is even some Microsoft technique to do it http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-dependency-injection#Exercise2. However, there are a lot of answers on forums against injecting services into Views using DI.
So the question: what is a right way to inject some services into Views? Or I shouldn't do it at all and something is wrong in the application design?
UPDATE: some real code examples (now we're using Model to inject the services)
Injecting texts from database (they have to be user-editable, as it is CMS):
<div class="steps">#Html.Raw(Model.Texts["Main", "Step2"]</div>
Injecting translations from database (actually, it is localization):
<div class="gonfalon">#Model.Translations["Title_Winners"]</div>
Injecting parameters (from database, could be request-specific; for example, if the site has different domains, facebook application should be per-domain):
Facebook.Initialize(Model.Parameters["FbApplicationId"], Model.Parameters["FbApplicationSecret"]);
The problem of current approach is that this code has taken from contest mechanic. It is definitely out of contest business scope to deal with custom texts, translations or facebook application Id. Also it ruins the Model as model models not actual business domain but deals with a lot of things actually belongs to View (like translations and custom texts)
UPDATE 2: Have modified the snippet from the answer below to be a bit more generic:
public static class WebViewPageExtensions
{
public static I ResolveService<I>(this WebViewPage page)
{
return DependencyResolver.Current.GetService<I>();
}
}
No, you shouldn't inject services into Views, but...
For scenarios such as theming where you want to give the theme developer more power, just one model isn't enough. If your model contains the current post for example, how can a theme designer asks for a list of categories for the sidebar? Or for a widget?
In asp.net mvc you can use extension methods to offer that functionality.THe extension method will use the dependency resolver to get the service. This way, you can have the needed functionality in the view without actually injecting a service.
Note that calling the business layer to update the model is still a violation of Separation of Concerns. THe services made available to the view should contain only read model or general utility functionality.
An example
public static IMyViewServices MyServices(this WebViewPage view)
{
return DependencyResolver.Current.GetService<IMyViewServices>();
}
IMyViewServices lifetime configured in the DI Container should be per http (scope) request
No, end of story. Why? Here is why:
Your view only needs to know what the view model it's going to be working with to present that model. There are couple of reasons for this but the biggest one is the separation of concerns. Keep your view as stupid as possible. You will see that this seperation will give you a clean application structure throughout the way.
There is a number of parameters user could change through the control panel that we need to end up in Views.
I'm not sure what you exactly mean here but this is why there are view models. Your business layer will shape models up, your controller will simply map them to your view models and pass them into the view (presentation layer).
This really depends on how much or little you want your controllers to do and to what degree of separation you want to achieve.
In my world, the "controller" in an MVC app does as little as possible because I have a service layer handling all of the business logic and a data layer above that handling all of the database interaction.
On a GET, the controller will simply call a service method that will build the view model and hands it back to the controller and the controller passes it on to the view. On POST, the view posts data to the controller which sends it off to the service layer for validation, saving to DB, etc. The service is injected into the controller's constructor.
I'd be more than happy to post code examples if you'd like to see them.

Understanding MVC4 Controllers

I'm fairly new to the .net Framework and the whole MVC programming philosophy. Could someone clarify and give me a basic explanation how controllers interact with sites using C#? I understand how to code in C#, and I understanding some aspects of the framework, but I don't see how they all tie together.
Model - Is a data structure that represents some kind of object (usually one). It's purpose is to read, write and manage the access to the underlying object with the aim to persist application state.
View - Is the components that are used to display a visual interface to the user, perhaps using a model. It might be a simple table or a complex combination into a full web page.
Controller - Is the user driven application logic layer the sits between views and models. It handlers user interaction, loads models, and sends views to the user. It determines what model is sent to the view depending on user requests.
The overall folder structure for an application might look like this.
>> Website
>> Controllers
>> Models
>> Views
In C# MVC each controller must have the suffix Controller in the name, they must extend Controller class and have a folder of the name prefix (without the Controller) in the views folder. This folder will then contain all the views related to particular actions on the controller.
Controllers can contain any number of actions defined as public functions. By default when returning a result from a controller action the name of the view must correspond with the name of the action. However you can also specify a view by name. When loading a view from a controller, it is possible to send an object as a model to the view and there by generate it's content.
Controllers can load any model and are not restricted in any way.
An Account controller defined as below with an action Login. The controller is placed in a AccountController.cs file in the /Controllers folder, and any views for this controller (Login in this instance with filename Login.cshtml) are placed in the /Views/Account folder.
Note: The naming convention has to be right as the names are used between the controllers and views to link the data.
public class AccountController : Controller
{
public ActionResult Login(string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index","Site");
}
return View("Login", new LogOnModel());
}
}
would be accessible via http://www.mysite.com/Account/Login. If the user is authenticated, the controller will redirect to the main site controller, if the user is not logged in then they are shown the Login view which loads data from the LogOnModel specified.
This is really just touching the surface of what is possible. Read some online information on some excellent articles by ScottGu which go into much more depth and talk you through how to use MVC.
ASP.NET MVC Framework Overview
ASP.NET MVC Framework How To - Part 1
// Part 2
// Part 3
// Part 4
Note : These articles are slightly outdated as they were written for MVC version 1 back in 2007, but the concepts of how the Models, Views and Controller interact still apply.
Controllers serve somewhat as an internal web service. They expose your server side code to your views and allow them to call the controllers. In terms of pattern, most people believe that controllers should be as thin as possible. If there is heavy lifting or other business logic, you should abstract it to another part of your application. In my eyes, controllers are there to provide the view with something to call, and then to return that data whether it be text/html, json, or xml.
Here's a great wealth of information, straight from the source: http://www.asp.net/mvc/mvc4
Specifically to the site, I'd highly recommend the tutorial. It will give you a much clearer picture of how Models, Views, and Controllers interact and depend on one another.
http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
A controller is a class which has methods, those methods are called actions, you atach those actions to "views" (cshtml files).
//This is your controller
public class HomeController : Controller
{
// This is your action
public ActionResult Index()
{
return View();
}
}
You can right click the "Index" action and select "Add View..." this will create a new view atached to that action.
In order to access that view you will do something like: localhost/Controller/Action
In this case it should be: localhost/Home/Index where Home = Controller, Index = Action
You should read about the MVC pattern
Microsoft has some really good tutorials for beginers
Controller in ASP.NET MVC is an object that handel your app logic in response of requests. It will be created per request (e.g. a HTTP request) and will be available until response created by View layer. After that it will be an unusable object (and soon GC will free its allocated memory) and for another request a new controller object must be created and so on.
I think by this definition it will be obvious why it must be lightweight and how you must use it.

Categories

Resources