Building a complex page in asp.net MVC - asp.net-mvc

I am currently considering the best way of building a relatively complex page in asp.net mvc. The page (and pages like it) will contain numerous 'controls' such as a shopping basket, recent news widget, login controls and more. In other words, it will be very component based.
My question is, what is the best way of building something like this in asp.net MVC? In regular webforms the answer would be simple thanks to user controls and the fact they can be nicely self contained. In MVC, I understand that in theory I should probably build a viewmodel that includes all the data needed for all my widgets and then render partial views in whatever page I'm building.
Could an alternative approach be to use javascript to load widgets 'dynamically' (think jQuery load) by simply calling into controllers that render partial views. That way I could have a basket controller, which when called renders out a basket. Of course, this relies on javascript....
Whats the best practise for situations like this?
Thanks

You could of course use JavaScript to populate the page sections but then this content will not be accessible to search engines (but that probably does not concern you).
What you need to understand that there is currently no way to make these partial views perform independently. Like talking to their own controller and posting data while having the rest of the stay unchanged (like it could have been done with WebForms and user controls). If you think postbacks and control state these things do not exist any longer. Your "control" makes a post, the controller has to process the request and then recreate the complete view along with all element values, states and other "user controls".
Unless you do it asynchronously with JavaScript of course. But then it's not gonna be an accessible page any more.

You can try SubControllers from MvcContrib or Steve Sanderson`s "Partial Request" approach.
But i warn you - communication between (partial requests, i haven't tried subcontrollers myself) them might get tricky and lead to mega failure. Use them only if you are completely sure that they are completely independent.
Anyway - that's a bad idea and should be avoided through controller/viewmodel inheritance or something....

My understanding of MVC is not yet up with WebForms, however is the generally accepted approach for stuff like this to simply throw these things in the ViewBag rather than include them in the ViewModel?

You could send down a main view model with some simple checks on it. Then render the appropriate Action if required. Then each partial could use it's own viewmodel and you wouldn't need to send everything down initially on the same viewmodel.
Razor:
#if (model.ShowShoppingCart)
{
#Html.Action("Index","ShoppingCart")
}
#if (model.blah)
{
#Html.Action("Index","blah")
}

Related

What is difference between View and Page in Asp.net core 2?

I am new in Asp.net core 2. One of the new things in Asp.net core 2 are pages.
But I can't figure it out
What is difference between page and view?
What are the benefits of pages versus views?
In what cases should the page be used?
Can I use both at the same time?
Really, your question is what's the difference between a Razor Page and traditional MVC. Both utilize Razor views. A Razor Page is self-contained (sort of). It has a code-behind like a Web Form, so technically you'd have a cshtml and a cshtml.cs file, the latter of which would act as both your controller and your model. Whereas, with traditional MVC, you'd have separate FooController, FooViewModel, and Foo.cshtml. Aside from some slight functional differences (such as having to use convention-based "actions" like OnGetAsync, OnPostAsync, etc. with Razor Pages) that's pretty much it.
The chief benefit to Razor Pages, as I see it, is its self-contained nature. All the code regarding a particular piece of functionality is essentially all in one place. However, the downside to this is that it can make code reuse difficult or at least not as intuitive in some places. Personally, I think the clear division of responsibilities offered by MVC is the more ideal approach and its also less "magical". One of the marketing touchpoints of Razor Pages is that it's stupidly easy. That may be true, but it owes its "ease" to abstracting away things web developers should actually be cognizant of, and that can be dangerous. If you don't actually understand how something works, you won't know if you're doing things right.
I'm biased, but to honestly answer "When should Razor Pages be used?", I would say never. I don't like the mixing of responsibilities, all the "magic", etc. Since they were introduced the number of ASP.NET Core questions here have skyrocketed and the majority of the Razor Pages questions are about things that are either obvious or at least more intuitive with MVC. That said, if you are going to use them, they make the most sense on CRUD type stuff - things that don't have a lot of functionality and are fairly straight-forward and/or repetitive.
Finally, yes you can freely mix and match Razor Pages and MVC. However, it should be noted because it's not obvious to everyone: Razor Pages only work as Razor Pages when used as Razor Pages. In other words, if you create a view with a code-behind (a Razor Page) and then use that view as a return from an MVC action, a partial, etc., the code-behind isn't actually utilized, just the "view" portion. Actually, to be more accurate, it is "used" but only to provide the model for the view in a general sense, since the view uses the Page in the code-behind as its model. However, this won't actually be "active", in the sense that page actions won't be hit, things likely won't get initialized properly, etc.

Do a full non-ajax post from a partial view in asp.net mvc

This more of an out of interest question than an urgently need an answer one, but I have been trying to find a good example of how to deal with a full postback from a partial view in asp.net MVC. The obvious example is the case where you have a small login form on every page. You can easily accomplish this through an asynchronous post back using jquery, but I am wondering if there is a way to do it without the use of javascript. I know it may be pedantic, but I don't like the idea of assuming the client has javascript enabled, particularly in this day and age where responsive design/ progressive enhacements are the big buzzwords around, so having you log in tied to javascript means that anyone on a simple mobile device won't be able to use it since their device probably won't support it.
Anyone have any ideas / examples of how to accomplish this? It's such a simple thing to implement in web forms I can't believe it's as tricky as I've heard it made out to be in MVC.
You just need a form within the view, that's all. The form will POST to its controller action method and generate a full page refresh (if that's what you mean by a full postback - I guess it is) irrespective of whether its a partial or not.
You can have multiple forms on a MVC view, and each one of them will give you a full page refresh, whereas with WebForms the pattern was one main form per page.

ASP.NET MVC: Am I doing it right?

So I am an old web forms guy and new to the MVC (in general, not only ASP.NET) framework. My views are starting to look a lot like the good old classic ASP. Not that i'm adding any business logic or anything, but more of a presentation logic. I end up with a lot of <% %> tags and if/else statements for deciding links to display or styles to use.
I also thought of deciding the styles or links within the controller and setting them on the model, but sounds like breaking the MVC purpose.
I end up ignoring the <% %> to make sure my HTML is well formed.
I want to hear your opinion. Are your views the same as mine? Am I doing something wrong?
If I have a ton of presentation logic, I try to move that to an extension off the HtmlHelper class.
Along with what mxmissle said (I voted him up) says I will do a partial view to move complex areas of a page to a seperate file, it helps clean things up as well as code reuse.
I find if things are looking a bit too old school ASP it's time to refactor. It's surprising what you can clean up into a helper class or partial view, or simply redo using something more concise.
Edit: Also, if it's looking a bit too old school ASP, perhaps you have logic in your view that doesn't belong there.
I usually create a ViewModel class specific for each view that contains any logic associated with the specific view. This is good for situations where the outcome of a condition is just a simple DIV or SPAN tag which don't really warrant their own extension or partial view.
I find it will clean up a lot of the classic ASP'ish look in my views.
See Stephen Walther's blog for more info on this approach.
Yes, you're doing it right. ASP.NET MVC isn't an improvement over classic web forms in every respect. It has its advantages and disadvantages ("tag soup", as you've discovered, being one of the disadvantages).
There are a few ways to alleviate the pain (moving as much logic into the model, HTML helpers, partial views, etc.), but it's difficult to avoid.

Using Code-Behind with ASP.NET MVC Views

Is it considered a bad practice to use code-behind with ASP.NET MVC Views? Got into a bit of a debate about this with my colleagues today and I was wondering the community's thoughts.
Obviously, this isn't an option when using another MVC like Rails, which makes me think it's relied on more as a crutch for those accustom to working with traditional ASP.NET Web Forms applications.
I would say that it's a bad practice to use code-behinds with ASP.NET MVC. MVC allows separation of concern where presentation logic (in Views) are separated from application logic (in Controllers). Using code-behinds will mix presentation logic and application logic inside the code-behinds, whereby defeating some of the benefits of MVC.
Certainly the authors of ASP.NET MVC In Action advise against it, and I agree. It isn't necessary, so why do it? In the early betas a code-behind file was included, but this was removed at RTM (or shortly before).
Typically, it simply encourages you to do more non-view work than you should in the view, as it is out of sight / out of mind.
I used code-behind extensively on my first ASP.NET MVC (Preview 3!) project - primarily for doing stuff like casting ViewData["foo"] into strongly-typed data objects, gathering view data into IEnumerables so I could loop across it, that kind of thing.
With the introduction of strongly-typed views, and pragmatic use of the (horrifically-named) Model-View-ViewModel pattern, I haven't missed code-behind at all since it was removed from the project framework just before the final release.
I now strongly feel that whatever processing you're doing in your view's code-behind, you are far better off modelling the result of that processing in your ViewModel, allowing the controller to perform the actual processing, and keep the view as simple and lightweight as you can. That'll let you test the processing logic, it makes the views easier to modify, and creates - I think - a much more elegant separation between transforming your data for display, and actually displaying it.
Yes the codebehind has long been the secret hiding place of business logic which as we all know should not be at the View level.
Code behind has been removed to stop naughty developers from being tempted.
I would recommend avoiding the codebehind in an MVC app at all costs. Using the code behind negates some of the values you get by using the MVC Framework such as separation of concerns, etc. You want to have your data access, business rules, type conversion and that sort of thing applied in the Model. If you find you need to convert your data types like Dylan mentioned, you may want to make ViewModels. The ViewModel would basically be the data from the actual Model you would like to display, in the format you wish to display it in.
Its probably best to avoid putting anything in the code behind when using MVC.
I would be interested to hear which part was being debated about, to go in the codebehind?
If you new to Asp.Net MVC, I really recommend spending some time going through the Nerd dinner example. There's a free EBook and source available here http://nerddinner.codeplex.com/.
Creating the simple demo from scratch is a great way to learn.
After doing this, it may shed some light on where the code you have in the codebehind, could alternatively go.
Note: If you do follow the EBook, grab the latest site.css file from codeplex, otherwise the virtual earth maps won't be aligned properly.
HTH
Ralph
It should be noted that "Code Behind" is a feature of the Web Forms view engine. It really has nothing to do with ASP.NET MVC itself.
For example, the Razor view engine in MVC3 does not even support it.
I would answer your question this way: If you cannot switch view engines without rewriting your controllers (or even your models) then you are not using the MVC pattern correctly.
Probably most of what you are doing in the .aspx.cs file should really be done before the model (or View Model) gets passed to the view. That said, in projects that I have migrated from ASP.NET Web Forms to ASP.NET MVC, I left a lot of the Code Behind in place. For example, I find it cleaner and more pleasing to use a Repeater control than to try to use a 'for' loop in Web Forms. I am still just iterating over View Model data after all. So why not? Separation of concerns is preserved (perhaps to a greater degree in fact).
I mean, why should "best practice" for Web Forms suddenly be the wrong way to do a Web Forms View? As a simple example, consider a Repeater that assigns a different CSS class to every second row of a table. Why should my controller (or even my model) care? Trying to put this kind of logic inline in Web Forms quickly devolves into tag soup and complete spaghetti. Now imagine something more complicated.
I have left Master pages in place that build the menus in the code behind. Again, all data comes from the View Model. I do not see why using GridView or other controls in this way should be a problem either.
I usually disabled ViewState in Web Forms anyway and did the data binding in "Init". Still, there would often be a small ViewState that I could not get rid of. I put some code in "Render" that moves this to after the form (it defaults to before). When moving to MVC, I sometimes left this code in. So, I have ASP.MVC sites that do indeed use Code Behind. I am just careful that it code that is specific to the view.
On new projects, I generally have found less of a need for Code Behind on most pages. Thankfully, view engines like Razor have made mixing code and mark-up in-line a lot less painful to write, read, and maintain.

Code behind in ASP.NET MVC

What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?
Here's my list of reasons why code-behind can be useful taken from my own post. I'm sure there are many more.
Databinding legacy ASP.NET controls - if an alternative is not available or a temporary solution is needed.
View logic that requires recursion to create some kind of nested or hierarchical HTML.
View logic that uses temporary variables. I refuse to define local variables in my tag soup! I'd want them as properties on the view class at the very least.
Logic that is specific only to one view or model and does not belong to an HtmlHelper. As a side note I don't think an HtmlHelper should know about any 'Model' classes. Its fine if it knows about the classes defined inside a model (such as IEnumerable, but I dont think for instance you should ever have an HtmlHelper that takes a ProductModel.
HtmlHelper methods end up becoming visible from ALL your views when you type Html+dot and i really want to minimize this list as much as possible.
What if I want to write code that uses HtmlGenericControl and other classes in that namespace to generate my HTML in an object oriented way (or I have existing code that does that that I want to port).
What if I'm planning on using a different view engine in future. I might want to keep some of the logic aside from the tag soup to make it easier to reuse later.
What if I want to be able to rename my Model classes and have it automatically refactor my view without having to go to the view.aspx and change the class name.
What if I'm coordinating with an HTML designer who I don't trust to not mess up the 'tag soup' and want to write anythin beyond very basic looping in the .aspx.cs file.
If you want to sort the data based upon the view's default sort option. I really dont think the controller should be sorting data for you if you have multiple sorting options accessible only from the view.
You actually want to debug the view logic in code that actuallky looks like .cs and not HTML.
You want to write code that may be factored out later and reused elsewhere - you're just not sure yet.
You want to prototype what may become a new HtmlHelper but you haven't yet decided whether its generic enough or not to warrant creating an HtmlHelper. (basically same as previous point)
You want to create a helper method to render a partial view, but need to create a model for it by plucking data out of the main page's view and creating a model for the partial control which is based on the current loop iteration.
You believe that programming complex logic IN A SINGLE FUNCTION is an out of date and unmaintainable practice.
You did it before RC1 and didn't run into any problems !!
Yes! Some views should not need codebehind at all.
Yes! It sucks to get a stupid .designer file created in addition to .cs file.
Yes! Its kind of annoying to get those little + signs next to each view.
BUT - It's really not that hard to NOT put data access logic in the code-behind.
They are most certainly NOT evil.
Ultimately, the question you ask yourself is this:
Does this code A) Process, store, retrieve, perform operations on or analyze the data, or B) Help to display the data?
If the answer is A, it belongs in your controller. If the answer is B, then it belongs in the view.
If B, it ultimately becomes a question of style. If you have some rather long conditional operations for trying to figure out if you display something to the user, then you might hide those conditional operations in the code behind in a Property. Otherwise, it seems like most people drop the code in-line to the front end using the <% %> and <%= %> tags.
Originally, I put all my display logic inside the <% %> tags. But recently I've taken to putting anything messy (such as a lengthy conditional) in my code behind to keep my XHML clean. The trick here is discipline - it's all too tempting to start writing business logic in the code behind, which is exactly what you should not be doing in MVC.
If you're trying to move from traditional ASP.NET to ASP.NET MVC, you might aviod the code behinds until you have a feel for the practices (though it still doesn't stop you from putting business logic inside the <% %>.
There isn't a purpose. Just don't use it except for setting the model
ViewPage<Model>
See this blogpost for more info.
At this Blogpost is a working example of removing the code behind.
The only problem I'm stuck with is that it is not able to set namespaces on the class.
The codebehind provides some of the strong typing as well as the intellisense support that you get in the view. If you don't care about any of these two features, you can remove it.
For example, I typically use the NVelocity ViewEngine because it's clean and pretty straight forward.
This is a great question. Doesn't MVC exist in the ASP.NET environment, without using the specific MVC pattern.
View = aspx
Controller = aspx.cs (codebehind)
Model = POCO (Plain Old C#/VB/.NET objects)
I'm wondering why the added functionality of MVC framework is helpful. I worked significantly with Java nd MVC and Java Struts several years ago (2001), and found the concepts in MVC to be a solution for the Internet Application organization and development problems at that time, but then found that the codebehind simplified the controller concept and was quicker to develop and communicate to others. I am sure others disagree with me, and I am open to other ideas. The biggest value I see to MVC is the front controller pattern for Internet development, single entry source for Internet Application. But, on the other hand, that pattern is fairly simple to implement with current ASP.NET technologies. I have heard others say that Unit Testing is the reasoning. I can understand that also, we used JUnit with our MVC framework in 2001; but I have not been convinced that it simplifies testing to use te MVC framework.
Thanks for reading!

Resources