Generating clean markup with Literal and string.Format - asp.net

In order to generate clean markup, I often resort to using code similar to this:
<asp:Literal ID="ltItem" runat="server">
<li class="{0}">{2}</li></asp:Literal>
And in the codebehind:
...
lt.Text = string.Format(lt.Text,
cssClass,
item.Url,
Server.HtmlEncode(item.Caption)
);
Some of the advantages are:
clean html markup, no ASP.Net WebForm id's etc
designer can do minor modifications in the aspx without developer intervention
code is precompiled (as opposed to use inline code or databind statements)
Disadvantages:
somewhat cryptic
fragile - when a parameter is removed in the markup, string.Format throws an exception
Therefore my question:
Is this a common way to generate clean markup? Are there better alternatives? Is the databinding syntax approach preferable?

It seems that you're fighting with your framework. ASP.NET web forms were designed to automatically resolve client-side ids and allow property-based UI customization that feels like Windows forms. These features often make a mess of the rendered HTML but the result is tolerated because of the perceived benefits.
If you don't perceive the benefits and find yourself fighting the ASP.NET web forms approach, consider another framework. There's no sense using a framework that doesn't share your values and goals.
If you want total control of your rendered HTML, consider ASP.NET MVC. Control of HTML output is one of its stated goals. In addition, it's designed to enforce separation of concerns.
If you're open to a non-Microsoft framework, there are many available including:
MonoRail - a framework inspired by Ruby on Rails
Maverick.NET - a .NET port of Java's Maverick framework

Correct me if I am wrong but using MVC won't gives you precompiled code isn't it ?
I do the same when using webforms and I had several issues with it.

Related

Why we don't used html tag control in our asp.net pages

I am trying out with asp.net . One thing i was surprise is that in our design code we don't used general <html>,<body> etc. but we used <asp:content> , <asp:button> etc. well i tried to find it out why but ended upon the abstract msdn pages . So please help me on this one
Tags with <asp:... tag prefix means they are "server side controls", which means:
they are accessible to your program on the server side (events, parameters, etc.) and by client side script (e.g. JavaScript)
they will be "rendered" (output when running/"translated to") as standard HTML tags when you actually run your web site
As an example, while you are building your web page/s the tag <asp:textbox runat="server" id=foo... will output as <input type="text" id="foo when you run the ASP.net application in a browser.
You can create a simple web page, run it in a browser, then VIEW SOURCE to see this "translation" at work.
So while you are developing/designing your web application, ASP.Net will provide you with what they call "controls" (e.g. button controls, label controls, etc.). They will all be translated into standard HTML tags/elements at runtime.
The above relates to ASP.Net technology called "Web Forms".
You can start with it - its a bit easier to program against. When you get more advanced and/or prefer to do more "bare metal" standard HTTP POST/GET, then you can look into ASP.Net MVC/Razor - this ASP.Net architecture will let you use standard HTML and pretty much control everything (which also means you need to know how to control 'everything').
There's nothing wrong with using HTML tags in ASP.NET pages, as long as you use runat="server" on them of course. I like to use a bit of both, dependent upon what it is. I suppose a benefit of using HTML tags means that you become more comfortable with the HTML and do not depend on the ASP.NET syntax.
On the other hand, in some cases, it would be an incredibly laborious task to actually write ALL of the HTML in order to replicate a control. Something like a complex DataGrid with all the events would be an absolute nightmare to write the pure HTML/JavaScript for. Using the ASP.NET control & syntax makes it much quicker and cleaner in that scenario.

asp:SqlDataSource vs ADO.NET coding with C#

I really do not have time to learn new language, in my case asp.net, but would like to start developing website in asp.net. I do not want to use asp:SqlDataSource control. is it ok if i write in codebehind aspx: all database connections and other CRUD operations in ado.net and c#. I already know xhtml, javascript - jquery, css, xml, json, some knowledge in sever-side coding (before php). want to start coding, instead of learning messy asp.net controls. Please advise, or I have to sit and learn all bloody ways of using those asp.net controls?
You do not have to use SqlDataSource control and you can do everything in ado.net and C#.
However, on certain case, you will be able to save quite a bit of coding by using SqlDatasource.
If you feel so bad about ASP.NET controls, why even aspire to use it? While you don't need to use any controls that the framework or third party offers, starting using anything new requires some learning. You don't need to use asp:SqlDataSource to build the data driven ASP.NET website but it seems like you have already shunned all the controls (not just this one) :)
Also, I would recommend looking in to ASP.NET MVC 3.0 if you are just starting. That would be more closer to what you have been doing so far.

Best way to handle common HTML Controls on ASP.NET

I was wondering, whats the best way to handle common HTML controls in ASP.NET? I mean, ASP.NET server controls generate too much crap inside the code so I rather use common controls.
But how about databind and how to manage those common objects correctly (such as combobox, textbox and so on)?
Don't forget that you can always set runat="server" on any control - that includes standard html form controls such as <input> and <select>, and also other elements like <div>. Anything, really.
This means that you can regain control of the html output in your WebForms pages quite effortlessly - as long as you don't need viewstate or any other more advanced databinding/state managing that ASP.NET normally handles for you.
That said, learning to use the ASP.NET MVC Framework is not a bad idea, since it helps you regain control of much more than just the html output. Generally, creating a page in ASP.NET MVC takes a little more work, since there are no drag-n-drop controls like gridview, textbox or even repeater. Instead, you use html helper methods and regular foreach loops, which means you have to type a lot more code. However, the MVC framework is designed so that you won't have to repeat much code anyway.
If you're concerned about the html markup generated by the WebForms ASP.NET engine, i suggest you take a look at ASP.NET MVC. It's purpose is specifically to give you the control you need over the generated html.
If you don't want to start learning ASP.NET MVC, ASP.NET 4.0 WebForms gives you more flexibility in the generated HTML (such as enabling the ViewState for a specific control only, setting the html id's etc.).
As for the databinding, again if you study MVC in depth and start thinking in terms of action -> result you can gain a lot more control and flexibility.
Later edit: I forgot to mention Razor, the new ViewEngine under development at microsoft. It's currently in beta and only inside WebMatrix, a very stripped down 'getting-started type' development platform for ASP.NET. MVC combined with the very clean code you can write using Razor will be in my opinion an important trend-setter in the web development world.
There's a reason ASP.Net controls generate all that "crap". It's so you can databind and manage those objects correctly. Using standard html controls is useful when you don't need direct databinding or if you have no need to manipulate the control through server-side code.
The best way to handle common HTML controls in ASP.Net is not to handle them directly. By using them to handle data and functionality, you're basically neutering .Net. You might as well go back to classic ASP.

Running ASP / ASP.NET markup outside of a web application (perhaps with MVC)

Is there a way to include some aspx/ascx markup in a DLL and use that to generate text dynamically? I really just want to pass a model instance to a view and get the produced html as a string. Similar to what you might do with an XSLT transform, except the transform input is a CLR object rather than an XML document. A second benefit is using the ASP.NET code-behind markup which is known by most team members.
One way to achieve this would be to load the MVC view engine in-process and perhaps have it use an ASPX file from a resource. It seems like I could call into just the ViewEngine somehow and have it generate a ViewEngineResult. I don't know ASP.NET MVC well enough though to know what calls to make.
I don't think this would be possible with classic ASP or ASP.NET as the control model is so tied to the page model, which doesn't exist in this case.
Using something like SparkViewEngine in isolation would be cool too, though not as useful since other team members wouldn't know the syntax. At that point I might as well use XSLT (yes I am looking for a clever way to avoid XSLT).
You can host ASP.NET Runtime in another application. See :- http://msdn.microsoft.com/en-us/magazine/cc188791.aspx
Also see http://www.west-wind.com/presentations/aspnetruntime/aspnetruntime.asp

Things I cannot do in ASP.NET MVC

Are there some things I cannot do with ASP.NET MVC?
Things that are only possible with ASP.NET WebForms,
or extremely much easier with WebForms?
We consider using ASP.NET MVC for a new project.
But I wonder if there are some obvious things we will not be able to do with ASP.NET MVC when compared to WebForms, or places where we will have to spend a lot of time with ASP.NET MVC.
The biggest one would be using existing 3rd party controls on your form. Most of the inbuilt controls are pretty easy to reproduce, but if you have a pet 3rd party control, you might have to host that on a regular (non-MVC) aspx page (luckliy this is supported).
Likewise, "web parts"
Also - the feature where ASP.NET uses different html for different clients (mobile, etc) becomes... different; you wouldn't want to do this by hand, but in reality most clients now work with standard html, so it is less of an issue in the first place.
Some things like i18n via resx files need extra work than is in the vanilla MVC template, but the samples are there on the internet.
One point... MVC is licensed only for MS/ASP.NET; so one thing you can't do (without violating the terms, as I understand it) is to run it in mono/Apache - but IANAL.
Now consider the things you can do with MVC, that you can't (or are hard) with vanilla:
routes instead of pages
automated input resolution (action arguments)
proper html control...
...enabling jQuery etc for simple AJAX
separation of concerns
testability
IoC/DI
multiple templating options (not just aspx/ascx)
re input resolution:
public ActionResult Show(string name, int? page, int? pageSize) {...}
will pick "name", "page" and "pageSize" off (any of) the route, query-string or form - so you don't have to spend lots of time picking out request values.
re templates - aspx/ascx aren't the only templating options. For example, see here; or you can write your own if you like... The view is not tied to ASP.NET controls at all.
Validation is not as easy as in WebForms. In Webforms you can add a validator and just set a property that enables clientside validation. You can localize the errormessage. The localization works clientside and serverside.
There is no out of the box clientside validation in MVC and you need to find a way to localize clientside errormessages.
Localization itself is different. Ressources obviously by default dont exist per page, because there is no page. But there is a good way to have ressources per view.
I still did not check, if it is possible to set SSL-required per folder.
EDIT
The story is different with MVC3. There is a good validation support now.
There are still things that are not implemented in MVC. The biggest issue for me is a complete implementation for donut cashing and partial cashing. There is some improvement in MVC3 in this area but it is still not complete. Anyway stay tuned: the MVC team seams to be aware that this is something they should work on.
The big one is Controls. User Controls are not available with ASP.NET MVC. I have even gone so far as to try using code like this:
new Label().RenderControl(...ResponseStream...);
No dice.
Of course, as a part of that, there is no need for view state, so that isn't in there.
Server controls do work, though.
As Marc said, third party tools and (serverside) webcontrols cannot be used. So slapping something together quickly by dragging and dropping a few controls on a form (like a grid and a dataaccess control) is no longer an option.
But with the codegeneration etc. you can still make something quickly. And you still have the above option if you need something quick.
I think view-state is non existent in MVC. You will have to track your own view state in some other way than the built in view-state in non MVC projects.
EDIT:
According to comments: "Getting rid of ViewState is an advantage not a disadvantage". – Craig
ASP.NET Ajax is not working with ASP.NET MVC so no UpdatePanel (due to lack of postback). Fortunately there is built-in ajax (Ajax.Form) which can be used to perform partial updates not to mention jQuery which is shipped by default with the Visual Studio project template.

Resources