Changing the View Engine in Asp.NET MVC - asp.net-mvc

I am trying to learn ASP.NET MVC by porting my current app written in ASP.NET Webforms to MVC. For starters, I am planning to use the Default View Engine (WebFormsViewEngine) as most tutorials/examples and the book I have use that as the default.
However, I know for sure that I do not want to use WebformViewEngine in the future and once I have a grasp of MVC, I would like to switch to a different ViewEngine (Spark seems to be interesting)
Would this be a simple change or would it take a lot of effort in terms of coding new views? What I basically want to know is which would involve more effort? Learning an alternate ViewEngine now or switching later?

OK - firstly you've got a decent sized investment in WebForms I'm assuming, and by virtue of that, you'll have a fair amount of user controls on existing forms etc. I'm sure you already know that this in itself is going to be the most work in the process, and has nothing to do with which view engine you choose because even the WebForms MVC view engine doesn't support user controls directly. This part of the work will still need to be done regardless...
Secondly, you probably are looking for a view engine that can take most of your other view built in logic and code (i.e not user controls), and by that I mean the stuff between the bee-stings ( <%= blah %> ).
Obviously the WebForms view engine does support this same syntax, but you also say that you specifically don't want to use the default WebForms view engine. Well you'll be happy to know that Spark also supports the <%= blah %> syntax, and this has been done specifically to support migrations like this.
Your best bet before deciding would be to watch this recent video here, and see how Louis goes through the simple WebForms-based MVC solution and it keeps running correctly even though the code still contains <%= blah %> syntax.
This support makes it much easier to transition and when you're ready you can then start moving your code to the more recommended way of using ${blah} syntax instead. But this can be done at your own pace whilst the overall functionality still works.
Hope that helps,
All the best,
Rob G

Looks like you can have a mixed bag of view engines in your application... link
Also check out this post from Phil Haack that shows using partials using different view engines to render on the same page.
This would allow you to simply switch over to the new syntax and not need to rewrite all of your existing views.

It should be as simple as calling
SparkEngineStarter.RegisterViewEngine(ViewEngines.Engines);
SparkEngineStarter should be a class in the Mvc part of Spark.
The documentation of spark is actually pretty good. Check out the section on getting it to run in ASP.NET MVC

Related

Is it worth migrating an existing asp.net-mvc project with webform view engine to razor?

I have a large asp.net-mvc web site . I recently upgraded to MVC 4 but one thing i am debating is it worth it to migrate to razor engine. I see there are tools to "auto" upgrade but i am trying to figure out if its worth the migration pain. I have about 100 total view (both regular and partial). If its a code base that i will have to live with for a while, is it worth the effort?
I know this may seem a bit subjective but given the size of my project I was looking for the expected cost of this migration effort versus the expected benefits.
Unless you have a specific reason, then IMHO no. Razor is a little, tiny bit (~5% according to most sources) slower than WebForms views however this may be old information. At best, they will render exactly the same speed. I have seen nothing to suggest razor is faster at rendering than webforms(ASP.NET MVC 3 Razor performance) and offers absolutely nothing additional that you cannot do with the WebForms markup.
Basically, its a more succinct markup language and can be a quicker to write and looks better than WebForms syntax. Lastly, if you organization has a legacy of writing WebForms code from back in the day, then all of the developers are already familiar with the WebForms syntax. No learning curve.
So - should you rewrite an entire application? No - you gain nothing. Going forward, should you use Razor? Depends, most 'seem' to be moving that way, it does look nicer and keeps the views a little cleaner.
If, however, you do decide to begin to update your views to razor, remember you can do this in steps. The ViewEngine will look for both types of views when determining what view to render. This does not have to be done in one fell swoop, but could be done gradually over time.
PS - This will probably be closed as a subjective question soon.
No, not unless you have a really compelling reason to.
The only real difference is the syntax on the views is a bit neater and there is an inherent "cool" factor working with a different view engine.
When razor first came out, we implemented a bit of a mixture, and so we're currently running a site with both razor and webforms views (this was implemented before razor became the default mvc viewengine).
We have written all new views in razor, and left the older views in webforms which we're slowly migrating across. But its for our benefit, not the customers or end users. So to migrate only the views across is a costly, timely affair that serves no real purpose...
If you've layered your app properly, what I would suggest (seriously) if you were looking at undertaking this, is to leave your existing website alone and create a separate stand alone site, using the new mvc infrastructure. There are definite gains from upgrading the site from an mvc 1 or 2 app to a new mvc 5 app.
We're currently doing this at my place of work, as our models, and logic are all in standalone dll' and we have very thin controllers. We're noticing a lot of changes and updates from the new mvc5 features that are now built in. Things like bundling, twitter-bootstrap etc are all things that we can use to ensure benefits that the customer notices.
Its the same old backend, but a shiny new face and thats worth doing.
I think your question is answered in past, if your objectives match with new features you should opt for upgrade, like mobile site support and more..
Old Post
this post gives details of MVC4 Release Notes and difference b/w MVC3 and MVC4 this both answer in this post will help you decide.
The MVC 4 improve those features(main points):
Refreshed and modernized default project templates
New mobile project template
Many new features to support mobile apps
Recipes to customize code generation
Enhanced support for asynchronous methods
For more details on MVC4, you can refer to: http://www.asp.net/mvc/mvc4
Edit: as the question is View specific,
The views works in the same manner in both version without any change,
you can try removing unwanted view engines
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
}
If you want rendering improvement, you must use the Partial View
<div class="news">
<h3>News</h3>
#Html.Partila("NewControl", Model.NewsItems)
</div>
Code Part:
public ActionResult News(){
NewItemViewModel vm = new NewItemViewModel();
vm.Items = repository.GetNews();
return PartialView("NewsControl",vm);
}
This will make the normal speed go increase by 10x
make sure the views are not combines and not passing any null models in view.
This should help in the performance issue.
If you'd ask me, since I've started using Razor, I'd never look back to the regular ASPX view engine. If you want to introduce fresh flavor to your application and the developers don't mind using the new Razor syntax (which is simpler and cleaner), go for it. If everyone is skeptical about that and application is doing well as it is, do not migrate. Since this question is inviting a personal comment, my opinion goes along with this, which (despite the fact Razor now seems to be negligibly slower than the equivalent ASPX) is obviously saying - migrate me, now.

Does ASP.NET MVC require you to use master pages?

My group is working on a new web application and is considering using MVC. However, there are members who would rather include pages than use master pages. Is this possible to do in ASP.NET MVC? In the small amount of time that I've poked around with MVC I have not yet been able to figure out how one might accomplish that.
Why the preference?
Having used both in the past, Master Pages are much easier to use. You just have to get over the (very small) learning curve.
ASP.NET MVC doesn't force you to do either one though...
If you like the Include method, then you would probably feel most comfortable using Partial Views to provide the same functionality. You would just add the Partial Views to each page instead of including another page.
No. It does not force you in any way.
You should really avoid server-side includes with anything newer than classic ASP. They're more difficult to debug, IIS has a hard time finding correct line numbers when there's a problem, etc. Also, I haven't looked at the order in which SSIs are processed in the request pipeline - they may not work at all with ASP.NET.
If you're moving into MVC, use RenderPartial() or RenderAction() instead. These perform essentially the same function as a server-side include, but are more inline with the spirit of the framework and provide some additional benefits, like passing models without having to declare a global variable (which should also be avoided, and I'm not sure if it is even possible under .NET scope rules).
And, no, master pages are not required, but you really should use them. Using includes to build your page layout works, but only if you don't and won't need to radically change the layout of your site at any point in the future. I'm in that boat now with a 350k line classic ASP app which used very nicely structured code and #includes to create the page layout. That was the best solution available at the time, but it's causing me a lot of headaches now (10+ years later).
With a master page you can move your ContentPlaceHolder blocks anywhere you want, whereas with #includes the final page really determines the format by the order in which the includes are placed. This also makes it pretty straightforward to create a mobile version of your site - you can create a mobile-specific master page and use the same content views.
Its a matter of choice,but for consistent look and feel across the web application, master pages give you just that. You have to take the team through the learning curve of good master page design, not only would it be useful for the current project at hand but also future projects. Good luck!
I would rather opt to go for Master pages due to the ease of use and built in support in MVC for this.
If you want to know more about it check out this tutorial: Creating Page Layouts with View Master Pages.
Grz, Kris.

Test Views in ASP.NET MVC2 (ala RSpec)

I am really missing heavily the ability to test Views independently of controllers. The way RSpec does it.
What I want to do is to perform assertions on the rendered view (where no controller is involved!). In order to do so I should provide required Model, ViewData and maybe some details from HttpContextBase (when will we get rid of HttpContext!).
So far I have not found anything that allows doing it. Also it might heavily depend on the ViewEngine being used.
List of things that views might contain are:
Partial views (may be nested deeply).
Master pages (or similar in other view engines).
Html helpers generating links and other elements.
Generally almost anything in a range of common sense :) .
Also please note that I am not talking about client-side testing and thus Selenium is just not related to it at all. It is just plain .NET testing.
So are there any options to actually do the testing of views?
Thanks,
Dmitriy.
The main issue with testing full views is that the asp.net view engine calls Response.Write in the supplied context / and not on the supplied writer.
The above is not the case for testing partial views, so for those you can use this solution:
http://www.brightmix.com/blog/renderpartial-to-string-in-asp-net-mvc/
There are other view engines that do allow you to test the view i.e. Spark.
ps. the concept in asp.net mvc is that you should be able to test the view by using the ViewEngine, but as I understand the asp.net mvc team didn't work around the existing asp.net engine restrictions to be able to do so for their view engine.
You may want to check out the UI Test Helpers that Eric Hexter and the guys with MVCContrib are working on. I haven't had a chance to look at it in depth, but it may help you. I found this link that shows some of the syntax: http://codepaste.net/cw8ie4
I would be interested to know what you find out as I will be doing this pretty soon also.
Interested to know if you find anything for .Net that does this. Our current app is WPF, but we are stuck with trusting Cucumber to touch our Views in all our Features... so yeah, that sucks. Hope you find something and update us.

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.

ASP.NET MVC Views - Can I use code-behind

I am new to MVC and I notice that the view pages can look pretty nasty with all the intermixed script tags. Does it make sense to generate the HTML in a method in the view code-behind and then just insert the string result of the method as a single bit of script?
For example: <div><%= GenerateTonsOfHTMLFromSomeIEnumerable() %></div>
Is this contrary to the MVC philosophy? Dumb for some other reason, like performance? Does it have any merit?
It's a matter of practice.
Here's an interesting read.
Codebehind files are evil
Codebehind files are not evil
Also there's an interesting article by "Rob Conery"
Inline Scripting and Code behind
So, the choice is yours. It depends on your application architecuture, how you want to structure it, blah-blah...
I guess the advantage with views without codebehind is that is is much easier to switch to different viewengine which doesn't support codebehind.
Though there will be some amount of work, but still it will be much seamless.
OK, chalk up another for the learning curve. I think I might have found the answer to my own question...
ASP MVC lets you install your own custom view engines which you can use (instead of the default ASP.NET view engine). So you can control the html generation. Once you know what to search for, its easy :)
Here's a good place to get started: Custom View Engine Example
#Rajesh - Thanks for the great links!
I wouldn't. You just need to forget about the codebehind file, seriously. In fact in MVC Framework RC1 by default there is no codebehind file for your views. Whatever c# processing you want to go on to render your view you can do it inline with your HTML. If you are thinking about doing some data processing, do yourself a favor and put it in the controller.
This is a paradigm shift, its best to just break your old habits now.
You can use code behind as well. It is only a matter of style preference.

Resources