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

2019-06-22 09:43发布

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?

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-22 10:20

You can use code behind as well. It is only a matter of style preference.

查看更多
Lonely孤独者°
3楼-- · 2019-06-22 10:23

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!

查看更多
The star\"
4楼-- · 2019-06-22 10:28

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-06-22 10:44

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.

查看更多
登录 后发表回答