MVC for a single page? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am not well-versed with MVC, although I have been reading up on plenty of its materials for the past days. Now, I need to make a web project that uses only one web page. The web page will display data from an existing database, as well as add and edit entries. I was told to use MVC. Although in my study, it appears to me that MVC is more appropriate for larger projects. How do I go about using MVC for my single-paged project? I was thinking something like dbcontext -> repository -> controllers -> models -> views. Would that be correct, or is there a more efficient way to do it?
If I were to not use MVC, what can I use?
EDIT: What would be the best approach in using MVC on a project with one page?

Yes You could. There are numerous approaches to this kind of task, I will name two of them.
MVC Approach
The MVC approach is as follows:
You will have one controller that will contain all your input logic and action results.
For example:
public class HomeController : Controller
{
public ActionResult index()
{
return view();
}
public ActionResult ContactUs()
{
return view();
}
public ActionResult About()
{
return view();
}
}
Then you create a layout page and a view (or Partial view) For each action, then you route in the same controller, this way creating a single web page that is only changing content inside the layout.
The Pros:
You contain all your logic inside one controller, thus create and easy to access code, as you know where all your input logic is.
You can use razor to control your views through your models, allowing you to create custom controls designed for your needs and properties, making it easy to connect with your server for get/post requests.
The Cons
Your controller can grow bigger as the website grows, thus creating a code that is "hard-to-maintain". The more pages you add, the more logic will be added to the home controller making the code in the controller long, unreadable and very hard to maintain easily.
Angular Approach:
The angular approach states, that you will have one action in the controller for beginning - index (aka home page):
public class HomeController : Controller
{
public ActionResult index()
{
return view();
}
}
You will then create a layout page and html pages to render inside it and then make your navigation with angular ui-router.
for example:
var myApp = angular.module('myApp', ["ngRoute"])
.config(function ($routeProvider) {
var baseUrl = $("base").first().attr("href");
$routeProvider.when('/',
{
templateUrl: baseUrl + 'Html/Home.html',
controller: 'myHomeCointroller'
});
$routeProvider.when('/About',
{
templateUrl: baseUrl + 'Html/About.html',
controller: 'myAboutController'
});
this way, you can make your navigation with angular 'location' dependency for example:
$location.path('/About');
Creating a layout page and a very easy to navigate system on this one layout page.
The layout page will only change it's content according to each html content.
The Pros
You create a very flexible and easy to maintain application, that will not consume alot of input logic (controller code) and will be angular controller driven, thus creating a very easy way to fix your code in the future as well.
The Cons
You cannot use razor in html pages, thus will have to create alot of ajax calls to your server, which will probably require you to write a web api or WCF to connect with your server in order to get/post data.
Your logic will spread in numerous angular controllers instead of one place (for example, all logic in Home Controller), this might take time when dealing with little problems that need attention.
It is your choice to decide which approach to take regarding the MVC.
There are alot of ways to do this with other frameworks but then again, it will never end.
Focus on your task as they told you, learn the principle of each approach that I told you and good luck on your way.
Material to read about views:
Views and partial views in MVC
Material to read about angular ui-router:
Angular routing explanation

If you need only one page application, you can use SPA template for ASP.NET Core: Building Single Page Applications on ASP.NET Core with JavaScriptServices.
They include are MVC ASP.NET + front-end MVVM frameworks like: Angular, Aurelia, Knockout or React.
Other option: use Razor pages for ASP.NET Core: Introduction to Razor Pages in ASP.NET Core:
Razor Pages is a new feature of ASP.NET Core MVC that makes coding
page-focused scenarios easier and more productive.

Related

How to separate the view and the controller in an ASP.NET application

I have an ASP.NET application that was developed by "programmers". This application contains all things which you should not do:
Hardcoded settings
Copy/paste anywhere (code not re-used)
Make a lot of small SELECT requests to the DB for each row instead of doing JOIN
Model, view and controller in one function
Etc.
Now, my goal is not to throw everything away and start over, but I want to separate different aspects of the MVC of the application. I do not want to start a new MVC project, I would like to evolve the existing solution into something modular.
For the controller, there is no problem, I can create classes that will manage DB connections, send mails etc. On the other hand I do not know how to separate the view and the controller.
The problem that traditional ASP pages myPage.aspx have an associated file myPage.aspx.vb and in this vb file there are both view management part(page elements, like dropdowns) and also the Business part (controller) which is executed on the button click.
I thought about making a call to a myPageControl.vb class that will contain the business part from the file myPage.aspx.vb, which will call the Model (db, mail, other).
(View: myPage.aspx.vb) -> (Control: myPageControl.vb) -> (Model: Db.vb, Mail.vb)
The problem is: how should I do to modify the page content from the controller, for example change a list value or display a text on it. I have to make a call to the View (to the other direction) and pass by parameter the class MyPage (.asp.vb)
I have already tried to find an answer to my question, but I've found only answers taking about MVC projects.
Does anyone have any idea how I should do it?
Seperation of Concerns was one of the main problems with webforms, and one of the advantages of MVC. In my opinion the best you could probably do is seperate the business logic into classes like you are doing now so code could be reused throughout the application, but completely "seperating" everything may require rebuilding the application as an MVC app.
The only answer I've found to this is to have the controller send the "data to bind to" to the page as XML. then all the page has is its page_load of course, and then a method to receive the XML and update itself from it. You can use smart naming structures so that you can do reflection and autobind from the xml to page elements.
Then on an action, have the page generate an xml of all the elements on it and their values, and send that through a "ProcessAction" method that determines the correct controller and calls the right method on the controller.
But as suggested, doing it over as an MVC project probably makes the most sense if that's the pattern you are going for. What I suggested works, but it will be as much or more work than just starting from scratch with MVC. Besides, remember that "support" for web forms is disappearing soon. It's not in (and won't be in) .NetCore, so it's days are numbered.

AngularJS Accessing C# MVC Index return Object

Morning all,
When I do use angularjs to do a http.get I can store the result
var response = $http.get("somethingUseful")
However, when angularjs handles the routing of the url (specifically the index page)
I've got:
Controller.cs:
public ActionResult Index (){
return View(new FunkyModel())
}
within
Index.cshtml:
#model FunkyModel
can access Model etc..., happy days!
though in
Template.html
what's the easiest way to then access this without doing a JSON.Encode or without having to make a second request?
Thanks in advance!
To be honest - it is not the proper way of using Angular + MVC. You shouldn't expect to share models between back-end and front-end code.
You should use JsonResult and send all the data to the view and let Angular load a view for you. In case it is not possible, another request for necessary data is a viable option(not ideal though).
In my opinion building MVC application with Angular on a front-end is a misunderstanding of concepts behind this technologies. Angular is the best when is used as a engine for SPA(Single Page Application), where you can use its routing features, views loading and many many more.

Umbraco and MVC and JSON

So I got pulled into a deep end having zero experience in umbraco and a tight deadline.
I don't know how umbraco works and how you integrate your MVC site into it really. A lot of headfuzz to get around.
basically the person I am inheriting it from created a basic controller from MVC and we can call the MVC site as we normally do.
I can also do JSON calls to the controller action which gives us back some data in a ViewModel. Great.
But when you browse to the site using umbraco and navigate to that same page, we run into big problems such as not being able to invoke the JSON call to get the data as it says object not found (in other words, the controller action is not found).
I read about umbraco basically overriding the default MVC routings but... why such a mess? :)
how can I integrate an existing MVC site into umbraco without much pain?
what is the url to call a controller action in umbraco integration?
say we have this:
public JsonResult GetPersonDetail(int id)
{
var vm = new AjaxPersonDetailViewModel(....);
return new JsonResult( Data = vm };
}
I can call this in JQuery like so:
/MyController/GetPersonDetail/1
so how do I do that with Umbraco?
Also try using this scaffolding package as well to get the initial bits for your controller in the right place http://our.umbraco.org/Documentation/Reference/Mvc/scaffolding.
Yes you can just manually create the files that the scaffolding process creates and reference them accordingly however i prefer to use that first then add/tweak the auto files to match what i need

Using MVC3 with folder structure like regular ASP.NET

So I am reading about building MVC3 projects and there is one thing that seriously bugs me. The folder structure of the project in no way corresponds to the path of the HTTP request. There is a bunch of things I like and would want to use, but having a flat folder structure is not one of them.
Why is this a problem? Well, I see it becoming a problem when building a site with a heavy mix of content pages and various forms/dynamic pages (most of our sites are like that), which would typically be done by different people. It seem it would be too complicated for client-side developers to follow routing rules of dynamic pages and/or creating new ones.
What I would like to understand is if there is way to configure MVC3 application in such a way that:
it follows directory structure for finding controllers without explicit route map for each one
views live in the same folder as corresponding controller
routing magic still works for actions and parameters
For instance I'd like to have a request /fus/ro/dah/ to try to find DahController in the \webroot\fus\ro\dah\ folder and execute its Index action. If not found it would look for RoController with Dah action in the \webroot\fus\ro\ folder, etc.
It is entirely possible that MVC was not meant to be working this way at all and I am just trying to force a square peg into a round hole.
UPDATE:
Looks like I can drop a view file into the desired folder structure, and it will be executed. However layout would not work apparently because it is expecting a controller. Does this mean I have to create a controller for pure content pages? That is a pretty crappy design...
UPDATE 2:
Main issue right now is that creating "fus" folder means that MVC will not even attempt to look for FusController... not under "fus" folder, nor anywhere else. Is it possible to get around that?
For instance I'd like to have a request /fus/ro/dah/ to try to find
DahController in the \webroot\fus\ro\dah\ folder and execute its Index
action. If not found it would look for RoController with Dah action in
the \webroot\fus\ro\ folder, etc.
MVC is not designed for a particular need like this, it is a general framework for building applications using model-view-controller pattern.
If you can't bend the application for the framework you can bend the framework for the application and honestly MVC is very customizable. [As a proof, in the current project (migration from ASP to MVC) that I'm working we have models as xml and no classes also we are using XSLTs for rendering. With a little work we have created custom components like custom view engine, custom validation provider, custom model binder... to make the framework best fit for the application and it does]
MVC is not designed and not forces to use it as it is and you can customize/extend as much you want. In your case you may have to create a
custom controller factory (because you want to customize the way in which the controller is seleced),
custom view engine (because you want to customize where the view is placed)
and may be others.
For custom controller factory you have to extend the DefaultControllerFactory class. There are lot of articles you can find through Google that explains about how to create custom controller factories.
Depending upon the view engine you are using you have to extend the respective one. For ex. if you are using web forms then you have to extend the WebFormsViewEngine and it razor then RazorViewEngine.
For more info. check this link
http://codeclimber.net.nz/archive/2009/04/08/13-asp.net-mvc-extensibility-points-you-have-to-know.aspx
you can mixup Asp.net and Asp.net MVC. as LukLed said, MVC is convention over configuration pattern. if you follow the convention. you dont need to configure. you can check this link for mixing up the asp.net content with MVC3
Mixing Asp.net and Razor
I believe ASP.NET MVC is not meant to be used that way. While you can configure MVC to do it, it is better to keep standard /controller/action/parameters URL format. If you have complex website with many different functionalities, areas may be helpful http://msdn.microsoft.com/en-us/library/ee671793.aspx. Every area get its own set of controllers, models and views, so teams working on different parts of website won't disturb each other.
While it may sound convenient, that framework first searches for DahController and executes Index action, then searches for another one, I find it bad idea. URLs should be clearly defined and Fus controller with Ro action shouldn't just stop working, because someone created RoController with Index action.
Look into using Areas as well. I think that helped me get over my folder structure issues with MVC honestly. So i could use the base folder as my Home details, then i could have a 'Admin' area which was a separate folder, things like that.
How "regular ASP.net" do you want it to be? If you want to do "legacy" ASP.Net Web Forms mixed in with MVC, you certainly can - re: mixing MVC with "file based aspx" - aka "hybrid". At the end of the day, it's all ASP.Net.
This is a standard MVC Application generated by Visual Studio. I've added a folder somedirectory where I want to use the legacy folder/file.ext paradigm and have a default.aspx Web Forms file:
Can I navigate to it via http://foo.com/somedirectory? Yes.
Can I use "pretty urls" too? Yes
Vanilla Global.asax generated by VS, just added MapPageRoute:
....
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//using "pretty urls" - ordering your routes matter.
routes.MapPageRoute("theWebForm", "legacy", "~/somedirectory/default.aspx");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
so now I can navigate to it via http://foo.com/legacy
Just check the order of your routes, and perhaps plan on your naming conventions so you don't have "collisions"...
Hth....

Workflows in ASP.NET MVC

As a learning exercise, I want to migrate an existing flash application to ASP.NET MVC. It has around 20 forms, and although it's mostly linear, there is some degree of alternate flows based on user decisions or data returned.
Could anyone point me in the right direction of how a controller would handle this? I don't want my views to have to figure out where they go to next.
Update
I think I may not be understanding the correct way of building this. I saw each controller as taking care of a different section of the app, and having a main controller being responsible for workflow.
If this is not the approach I should be taking, what is the best way of doing this?
Update 2
Would Areas in ASP.NET MVC 2 take care of this sectioning of the app? I really don't like the idea of having too many actions in one controller...
In general:
Controllers are usually a collection of actions that deal with a logically coherent chunk of the application ( hence why you often see UserController / OrderController etc etc ).
MVC applications should be built using PRG ( post - redirect - get ) which means you will have 2 actions for each form, one that will display the form and the second, with the same name but decorated with [AcceptPost], that will process the form and redirect the user to the appropriate location based on the result.
The simplest way to learn how this works and migrate your app over is model each form as a simple dto with no logic, build a view for each form and 2 actions.
Once you have the logic working in the controller, you may want to migrate it out into some form of service that can be injected into the controller.
Specifically for your workflows:
Each workflow should probably have it's own controller. It may be useful to model them using some form of state pattern ( depending on the complexity of the workflow ), and providing a result from each state transition that your controller can translate into a redirect to the next step in the workflow.
When a form posts to a controller action it is the controller action to decide what to do with the posted results and which view to render next or redirect:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult HandleFormSubmission(FormCollection col)
{
// do something with posted data
// redirect to /someOtherController/someOtherAction
// which could show some other form
return RedirectToAction("someOtherAction", "someOtherController");
}
I was struggling with the same problem (using Windows Workflow Foundation with ASP.NET MVC) and I blogged about it here
Maybe you'll find it helpful, sorry for pushing my own link

Categories