Web Parts with a markup file? - asp.net

I'm an ASP.NET web part novice. I've built a few simple ones using only a class that derived from WebPart and overriding the CreateChildControls method, but nothing really very substantial. My question is whether it's possible to have a web part that also takes advantage of a separate html/asp.net markup file that will help provide some structure to the web part's output. In the past I just created server controls and added them to the controls collection, but this seems like a silly way to try to create a non-trivial layout. Can I do this? Do I have to use an ascx user control or can I bypass that step? There are a lot of hello world tutorials on web parts out there, but none seem to go past the CreateChildControls override. Thanks!

Yes, there is. Go here to learn about templated web parts, and go here to see all of the info he has on WebParts. I used this technique back in 2004/2005 and it worked very well.

The links in the above answer are no longer working, but here is an alternative one:
http://www.a2zdotnet.com/View.aspx?Id=95
In VS 2010 we also have visual web parts, that I think do pretty much the same trick but it's wrapped in a project item. I've only seen this in the context of SharePoint so not sure how it works for ASP.NET projects. Here is an example:
http://msdn.microsoft.com/en-us/library/ff597539.aspx

Related

Asp.Net inline (single-file) vs code-behind

In the transition from classic ASP to Asp.Net some developers took to putting their server side code in a block at the top of their HTML ala:
<%# Import Namespace="MyDll" %>
<script runat="server">
void Page_Load()
{
}
</script>
This single-page model has some advantages as Jeff Atwood describes, however, in my experience I have seen nearly all code put in a separate code-behind file in recent times (ie with VS 2008).
Nevertheless, it turns out a colleague strongly prefers the single file (inline) method over the separate code-behind method.
What are the strengths and weaknesses of each approach? (I've noticed that code collapsing and #regions don't seem to be supported. Also the pages get rather long and there is no longer the visual separation of client and server side code. Can you tell I have a preference?)
I realize that variations of this question have been asked before, but I haven't seen anyone actually spell out specifically the pros and cons of each method.
EDIT
Thank you everyone for your thought provoking answers. I'm still hoping for a list of strengths and weaknesses of each method. What are the actual features that each has (or doesn't have)?
There's no doubt in my mind that the code-behind or mvc models are superior for almost everything you want to do. However, even today I still find myself using inline code for most of my pages. Why? Because there's one big scenario where the inline scripts really shine.
If you have a large amount of legacy ASP Classic code that you don't want to just throw out, including a deep nesting structure, it all lives in one big application, and you want to share that application with your asp.net code, you can just drop inline asp.net pages right in your existing web file system and they'll just work.
This sounds like exactly where your other developer is coming from.
Because codebehind is just a class it has all of the advantages like inhertance and interfaces. It also enhances readability.
Single page has mostly been replaced by mvc for applications that focus on outputting data instead of implementing businesslogic.
Have you considered looking at ASP.NET MVC instead? It will allow you to overcome this dilemna in a very clean seperation.
Generally, when working in WebForms, the trend I've seen is to use a code-behind. Many* WebForms applications that I've seen in the field have too much in their code-behinds, and the separation is almost critical just to be able to understand all the logic.
However, in a well-designed app where the UI is only doing a UI job, and passing all the logic and heavy lifting to a different app layer, a single-file solution will often end up being more elegant and easy enough to traverse. In a way, going with the single-file solution may -- in the right hands -- motivate a better separation of concerns, because you don't want that one file (which provides your UI) to get cluttered with a bunch of business logic.
In the ASP.NET MVC model, the default is single-file. This is, again, to stress separation of concerns and good application design. (I do not know off the top of my head if the ASP.NET MVC kit provides a code-behind concept. I have not used it if it does.)
Ultimately, YMMV. Good developers tend to write good code whether it uses the code-behind or single-file model. Bad developers tend to write bad code either way, too.
* Obviously not ALL!
Inline code is procedural in nature and lacks separation of concerns...
One of the selling points of ASP.Net was the the code-behind and the server controls. It was thought to be bad to have inline code. This changed when ASP.NET Mvc came on the scene -- inline code became "hip" again.
If I had a choice and all things being equal using the code-behind is a better approach. I strive to keep as much logic/code out of the UI.
Even using the code-behind, while it is a class, it can become a tangled mess. I found that using MVP or some variant of MVC with web forms made development more maintainable in the long run.

Should I learn ASP.NET if I prefer to have fine-grained control over my site's HTML?

For months, I've been considering downloading Microsoft's express web platform and learning ASP.NET, which I might actually enjoy, seeing as I already do web work with PHP, but am much more comfortable with C#.
However, the primary reason I don't want to do this is that I've always associated ASP.NET with useless spaghetti HTML. The link I posted is an excellent example. Would it be possible to use ASP.NET in a context more similar to PHP, using it to power my site but not leaving the HTML, CSS, and JavaScript to be done by hand for validation and semanticity reasons?
EDIT
I've decided I'm not going to learn ASP.NET and stick with PHP.
While MVC sounds nice, for me it will likely end up being a development/debugging headache.
Things get much better if you use ASP.NET MVC. I recommend you skip ASP.NET WebForms and jump to MVC directly.
If you are going to use Classic ASP.NET Web Forms, you really need to learn how it works to avoid truely ugly html. If you know what you are doing, you can get close to what you want (you can't completely get rid of ViewState & it will do some ugly thing with element IDs)
A lot of the ugliness of Classic ASP.NET occures when people write web forms like they wrote VB 6 Windows applications.
ASP.NET MVC is a good option. It may be the way to go as a starting point; I would like to switch to it myself. I guess my point is that you can get less ugly HTML using Classic ASP.NET.
you're really going to want to check out the asp.net mvc. it allows you to develop in a manner a lot more suited for the web than vanilla webforms.
First of all, ASP.Net, even using webforms, does allow you to have complete control over the markup output. Of course it's easier for some cases than others, but anywhere you find you're not getting the html you want out of a control you can always replace the render behavior with a ControlAdapter.
That said, as others have mentioned you'll probably find it's much easier to get the exact html markup you want using ASP.Net MVC.
MVC.net and WebForms are built upon ASP.net
You can get a decent amount of control with webforms by disabling viewstate and not using any controllers (or very few). Its all in how much you let it do for you
If you are looking to acquire skills in the latest and greatest, then MVC is where you should start but I would also consider whether you will ever be asked to support ASP.Net Webforms. Having an understanding of ViewState is crucial to that end.
For fine grained HTML output, you can produce this in many different ways with classic ASP.Net. There is a growing group of developers who are using a mixture of ASP.Net and microtemplating with Javascript to produce RIA's. This inevitably leads to keeping your html output cleaner so that it can be manipulated with jQuery and CSS.
Learn ASP.NET MVC as it will give you more control over the html generated. Also learning ASP.NET will increase your job opportunities significantly.
My first real development in ASP.NET was with MVC, and I must say I truly miss it now that I'm onto the next project using webforms. Each has it's place and webforms is working pretty well for what I'm doing (also using it as an opportunity to learn about TableAdapters and what not) but I really do miss being able to insert the data I need right into the HTML. That way I know the layout I've built won't get screwed up.
As a framework I enjoy ASP.NET quite a bit, but the controls on the page seems so far removed from anything resembling HTML that there is often a mental disconnect with what I'm typing with what I'm expecting to see. I was that way when I first started HTML though, so I imagine I'll get used to it. When I started with MVC it was overall a much more enjoyable experience coming from a front-end background.

Seeking advice on de-bloating asp.net 3.5

I’m new to .net, though I’ve been writing in classic asp for years. I know it’s time to make the change, but I can’t stand how bloated the HTML becomes.
For example, a simple menu using a web.sitemap and adds over 100 lines of JavaScript and HTML. A simple form with server-side validation adds in masses of ugly JavaScript. And a basic table of data using GridView adds in a ViewState that makes my eyes water.
Call me a purest, though I don’t like sending data to the browser unless it’s needed. And I don’t need a form-riddled menu when a simple unordered list of links will suffice.
So, set in my ways, am I destined to forgo the benefits of the Framework entirely by insisting on writing my own, cleaner code for everything? Or am I missing the point?
As a brief aside I’m a big fan of Campaign Monitor, a newsletter distribution company. They’ve written an elegant and comprehensive user-interface in .net without a single ViewState or bizarre .net-mangeled ID reference. Even the Sign Up form on their website (/signup.aspx) is as clean as a whistle. What’s their secret?
I hope I not the only one. Any advice would be greatly appreciated.
Try ASP.NET MVC or one of the other MVC web frameworks for .NET
If your GridView doesn't need it, then turn ViewState off for it.
Also, please edit your question to say what version of .NET you're using. Some of this gets better, and some does not. You might also want to try VS2010 beta 1, and complain about anything it doesn't fix.
Another idea would be to go on treating ASP.NET like it's classic ASP. Do it exactly the way you're used to, but do it with the idea in mind that there's about 10 years of development work that's gone into solving some of the problems of classic ASP. Once you actually hit one of those problems, find out if ASP.NET has solved it, and how.
For instance, I have a hard time believing you enjoy writing FOR loops to generate table rows. If you get tired of that, learn to use a Repeater control, or a DataList control, or even the old DataGrid control. If you turn ViewState off on those, I think you may find the generated HTML to be acceptable, and you'll find it a lot easier to generate tables and other structures that repeat based on repeating data.
You can opt-out of much of that bloat by not using all the out-of-the-box controls that come with it but I prefer the MVC route that activa suggested
Here is my list:
Keep the use of asp controls to minimum
Turn off Viewstate when it's not need
If you don't want the JavaScript associated with Client Side Validation (with ASP.NET Validation) set the EnableClientScript to False
Use asp:literal instead of asp:Label
Yeah it seems to be that everyone is bashing webforms at the minute for the reasons you have outlined above. HTML heavy Controls, ViewState, no control over ClientIDs all seem to cause an issue with people.
However let is be said that you can use asp.net (webforms) and produce some decent applications.
Control of html is yours through httpModules and httpHandlers and some of the issues mentioned above are fixed in asp.net 4.0
I just listened to a great podcast comparing MVC and webforms. Its in the area you are asking about. Also check out this blogpost by a dotNetNuke regarding the good asp.net code and why people should take a breath before converting everything to mvc.
Having said that I've tried Asp.net MVC and it is awesome. I'd probably look at dotNetNukes code to as its a mature asp.net product.
Also, when you do want to use these newfangled server controls, check out the css friendly control adapters. They clean up much of the bloat.
For client IDs the key thing to remember is to let the framework handle them. If you need to get an element on the client side, remember to emit the control's ClientID property into your script.
I've been using a template system and am very happy with it. Basically write an http handler for .html files and put tokens in the html files that regex could find in one sweep and inject any stuff. (google template c# for more info).
I tried some of the supposedly cool new features of ASP.NET for a little while. I also didn't like most of them. I felt constrained to work within the limitations of the common paradigms Microsoft had dreamed, even though I new how easy it would be to produce the HTML and JavaScript myself to do specifically what I wanted to do without having to learn how to jump through the hoops of so many new Microsoft-specific idiosyncrasies.
Anyway, I stopped using the parts of ASP.NET I didn't like on new code I've been writing lately. When I first started using ASP.NET, nothing in the MSDN documentation jumped out at me about how to avoid such complications, so I posted a couple "Hello, World" at http://www.agalltyr.com/rawaspdotnet.html to help spread the heretical word. I couldn't care less if it's the latest cool technology or the recommended technique. It's a reliable and reasonably efficient tool I can use to do my work.
Oh, and I'm not in the mood to learn ASP.NET MVC either. That's just more idiosyncrasies. Give me a language (C#) and a framework (.NET), and I'll design my own abstraction, thank you.

ASP.NET MVC users - do you miss anything from WebForms?

There are lots of articles and discussions about the differences between ASP.NET WebForms and ASP.NET MVC that compare the relative merits of the two frameworks.
I have a different question for anyone who has experience using WebForms that has since moved to MVC:
What is the number one thing that WebForms had, that MVC doesn't, that you really miss?
Edit
No-one has mentioned the WebForms validation controls. I am now working on some code that has a few dependant validation rules and implementing client-side validation for these is proving slow.
As a PHP/Classic ASP person, I ventured into webforms world about 5 years ago. After having to handcode things like table grids, calendars, etc, in scripting languages, it seemed like webforms would be a tremendous helping-hand. It was...that is until you need even a slight bit of customization beyond alternating row colors and the like. Yeah, you could have a gridview running with a few drag-and-drop motions. But customizing even what would seem like a simple thing could turn into hours of torture and research.
I also think a lot of the examples given in .NET online are oversimplified for the effect of making webforms look "easy". Sure you can get that gridview to show only 10 records of a 100,000 record table, but do you realize that ALL of the records are being loaded into memory by default? As an example of the over-complicatedness of rectifying that problem, I spent a while creating a pageable gridview that only loads chunks of records, but it wouldn't work. After an hour of research, I found that you had to delete an extra property that the IDE inserts into the codebehind. Not fun when stupid stuff like that sets you behind.
And at every turn, it happens.
Don't even get me started on viewstate.
But then the clouds parted, and .NET MVC was handed to us. Now THAT is a framework. If you are a web developer, you should know whats happening when someone makes a request to your webserver. The abstraction and layer of cruft that webforms put on top of that is a disservice.
For the most part, I'm able to develop applications at the speed of PHP scripting and FINALLY have TOTAL control over the UI. That's what it's all about.
And as an additional note: People need to stop complaining that they are creating "tag soup" in MVC views when they find they have to use <%= %> tags and the like. Drag and drop your gridview onto the page, set all the properties, then view the crap it gives you. And your not nearly done yet, now you have to attach events and put more gridview-related code in your codefile. Talk about messing up the coding experience. I'll take a simple foreach loop anyday.
nothing :)
I really like the way ASP.NET MVC works. I want to control my HTML. I don't need controls. We can get the same functionality with HTML helpers and third party tools, e.g. jQuery and all the available plugins.
Here's an example on how to use a gridview-like with jQuery grid on ASP.NET MVC.
Although Ruby on Rails is a more mature framework, I do think that ASP.NET MVC is on the right track.
I miss the gridview, the simplicity of getting built in sorting and paging in with very little effort. I use grid functionality all the time and have still not found a good alternative in mvc
Well I do miss something :
the ability to have a pageable grid in seconds.
Although it wouldn't be very fair since I also had to create a class to feed to the ObjectDataSource to have an efficient pagination. And also the pagination would work only with the JavaScript on or I would have to write code to read the QueryString (for ex. &pag=2 etc.) and so on.
In fact... I guess there isn't much too miss.
The simplicity of having only one form on a page. I think the html form functionality is kind of awkward and not very intuitive and I guess there is a good reason why the webforms creators tried to abstract away form handling in webforms.
One difference, which I am sure will be rectified over time, is the expansive amount of reference material and examples online for web forms versus the relatively sparse amount for MVC. However, one could argue that a lot of the material on web forms covers topics such as the page life cycle which MVC no longer makes necessary (thank goodness).
Until now nothing really.
I definitely miss MVC every day at work while I look at the ugly WebForms code I want to wipe it all out and now make everything transparent, clean and beautiful.
Of course only time will show whether the new girl is really better than your old wife.
As crazy as it sounds, I miss the calendar control. Not for datepickers or that sort of thing, but for scheduling apps where you want to show a full page month-at-a-glance/outlook style events calendar with selectable or clickable links that you inject via the day render event.
If anyone knows of an MVC alternative, please share! Rolling your own in this case is doable, but kind of a pain.
Viewstate is the thing i miss - until i remember problems it causes.
Then i bend my mind and look for another approaches (smarter model binding, ajax etc.) which usually turns out to be better (but slower to find & implement).
The main thing I miss is the documentation. WebForms, because of it's relative maturity, has a lot of official documentation and also a lot of 3rd party examples and snippets available. However, this is improving all the item and, as MVC gains momentum, I hope it will be on a par.
Nothing as well.
WebForms do so much automatically but frequently I had to hack it to suit my needs.
MVC let me do what I want and I can hack it to get things done better/faster.
I love to control the output and prefer clean, lightweight style.
Output Caching is not really implemented in ASP.NET MVC (as of version 2). There are tricks to get it working, like using Web Controls with the OutputCache directive, or using WriteSubstitution, but all these tricks go against the nature of MVC in some way. Output Caching for anything other than entire action methods is really tricky to get working in ASP.NET MVC, and always induces enormous technical debt. Since Output Caching, especially in the newer versions of IIS, is incredibly performant compared to data layer caching, this is a shame.
simplicity in Dragging and dropping controls.
might be seeing some of this in the near future maybe in mvc4
Reference :- http://www.codeproject.com/Articles/808297/Things-you-will-miss-in-ASP-NET-MVC-as-an-ASP-NET
I will not say i miss because all the changes are happening for good. But yes i would miss the below
The lovely server controls who just give output in a blink.
The behind code file.Double clicking and going to the Code behind for some reason made me superior.
Viewstate magic.
Now i need to get in to headache of POST and GET.

Conditional Display in ASPX Pages on Sharepoint

I wonder what the best practice for this scenario is:
I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.
Two solutions:
Change the PageParserPath in web.config as per this site
<PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx"
CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
Create all the controls and Wire them up to Events in the .CS File, thus completely eliminating some of the benefits of ASP.net
I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible.
So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too.
You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.
What does the ASPX page do? What functionality does it add? How are you adding the page into the site? By the looks of it this is just a "Web Part Page" in a document library.
I would have to do a little research to be 100%, but my understanding is that inline code is ok, providing it's in a page that remains ghosted, and thereby trusted. Can you add your functionality into the site via a feature?
I would avoide option 1, seems like bad advice to me. Allowing server side code in your page is a security risk as it then becomes possible for someone to inject malicious code. Sure you can secure the page, but we are talking remote execution with likely some pretty serious permissions.
Thanks so far. I've successfully tried Andrew Connel's solution:
http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx
Wrapping it into a solution is part of that, but the main problem was how to get the code into that, and it's more leaning towards Option 2 without having to create the controls in code.
What I was missing:
In the .cs File, it is required to manually add the "protected Button Trigger;" stuff, because there is no automatically generated .designer.cs file when using a class library.
Well, it's a page that hosts user controls. It's a custom .aspx Page that will be created on the site, specially because I do not want to create WebParts.
It's essentially an application running within Sharepoint, utilizing Lists and other functions, but all the functionality is only useful within the application, so flooding the web part gallery with countless web parts that only work in one place is something i'd like to avoid.

Resources