Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 269
RAL Avatar asked Dec 10 '08 04:12

RAL


3 Answers

It's a matter of practice.

Here's an interesting read.

  1. Codebehind files are evil

  2. Codebehind files are not evil

Also there's an interesting article by "Rob Conery"

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

like image 126
rajesh pillai Avatar answered Sep 28 '22 03:09

rajesh pillai


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!

like image 32
RAL Avatar answered Sep 28 '22 05:09

RAL


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.

like image 21
Al Katawazi Avatar answered Sep 28 '22 05:09

Al Katawazi