ASP.NET HTML Helpers vs Generic HTML - asp.net

Are there any real benefits to using ASP.NET HTML Helpers over Generic HTML?
For me, I really do not see any "major" advantage. What do you think?
Update:
How flexible is it with Javascript/JQuery?

Depends what you want to do with posted data. If you'll just read form variables in controller action, then it doesn't really matter, but if you plan to use internal model binding, it may be much more tedious for you to write manual HTML.
Another plus with HTML helpers is when you want to create some more complex parts of your document like:
Html.CheckBox()
Html.ValidationMessage()
etc.
Checkbox itself creates two inputs. A checkbox and a hidden field that makes it work with checked/unchecked state properly.

HTML Helpers are useful, when you want to reuse a piece of C# code and render some HTML dynamically without creating a full blown control.

Related

Do I need HTML helpers in my View?

Right now I just output my value(s) like
<input type="text" class="form-control" value="#Name" id="name" placeholder="Name">
But I've seen a lot about #HTML display something?
Should I use HTML display, and if so, how and why?
The Html helper class is there to encapsulate writing a lot of html code in a single call:
- the actual field
- validation rules according to your model Field Attributes
- the validation place holder
- Value binding
additionally, allows you to change the behavior and html of all your fields in case needed, in one spot.
it is, like many other things, a tool...
use it if you wish...
for my opinion, it rule and should be used.
You can do it either way. #Html.TextBox and #Html.TextBoxFor will automatically generate the html for you, but you can do it yourself if you want.
Personally, I prefer writing my own html, but that's just me...
The # symbol allows you to access c# code within your cshtml file so you can mix html and c# code to generate a final html output. For more information, search for C# Razor syntax, here's a link for more info http://www.w3schools.com/aspnet/razor_syntax.asp and http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/
The benefit of using Razor syntax is the ability to access helper c# methods, global variables, view model variable object passed from the controller, view compile time errors (by default, it's off in visual studio, check http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx/ for more info), you don't need to use javascript to populate a form or other fields dynamically ...etc
The downsides are your code needs to be compile to html so browsers can process it, a syntax error can crash your whole page, your cshtml code is not portable in case you decide to switch backend engine, ...etc

Best way to output undetermined html (c#)

I'm in the process of creating a survey system. This survey can have any number of questions of any html input type and the questions can have any number of options. Currently, I'm looping through this data and building the html using StringBuilder and then applying it to a div using innerHTML. Considering the complexity of the html, I found that StringBuilder would be the best option.
I'm researching other ways to output this data, one being Repeater, but a repeater or any other control doesn't seem fit for this task. I don't have a problem with using StringBuilder. It gets the job done. However, some people frown on using StringBuilder. I would like to hear other peoples input on this.
You are probably better of using some of the webcontrols, rather than generic html.
For example, you can create a table, and bind textbox, checkbox and listbox controls to this at runtime based on the questions. You can then loop through these and read the values on postback.
In my opinion, this will be a lot simpler than writing the complete html output and then writing a handler for the submissions.
If you find yourself preferring to use StringBuilder, rather than an ASP.NET forms controls to build html I'd honestly suggest switching to using ASP.NET MVC rather than ASP.NET forms. It supports creating views in a much more natural way for that sort of use.
I'm firmly in the camp that agrees with #ChrisBint. Use custom controls...
HOWEVER - There are situations - even within custom controls (which, for all we know, you're already using) - where you NEED to do stuff like this.
In that case, I would recommend implementing a custom server control using HtmlTextWriter to generate the output - which is what MS uses inside their controls:
http://msdn.microsoft.com/en-us/library/system.web.ui.htmltextwriter.aspx
Writes markup characters and text to
an ASP.NET server control output
stream. This class provides formatting
capabilities that ASP.NET server
controls use when rendering markup to
clients.

Critique this strategy

I want to populate a gridview by using jQuery and AJAX. From my calling page jQuery will call a handler (.ashx) that will deliver XML data or HTML markup for the gridview. As I see it I have two choices: 1) deliver XML which is then bound to the design-time gridview on the calling page, or 2) deliver HTML for the gridview. My first question is: which method is easiest?
Now there are two factors which complicate things. First, the gridview must be sortable on all columns. Second, the data will be filtered (some columns will be hidded) by user configuration options which are also to be stored in the database. Knowing this, does your answer to the first question change?
Any comments, insights or gotchas are appreciated.
Dewey
I did something very similar to this on a recent project. I used jqGrid for display purposes - it can easily be bound to JSON-formatted data (and probably XML-formatted data too), and it supports click-column-header-to-sort. I would definitely recommend it for functionality and ease-of-use.
I didn't have to implement user-configurable showing/hiding of columns. However, it could be done with jqGrid pretty easily: the grid columns are configured in javascript, so you could use code-behind logic during the initial page-build to customize the javascript which defines the column configuration.
I definitely wouldn't return HTML from an ASHX class, since you'd have to craft all the HTML by hand using StringBuilder (or something similar). Makes the code tougher to maintain; and if you ever want to change the page layout, you need to re-compile and re-deploy your system. If you desperately want to return fully-formatted HTML, I would probably use jquery/ajax to just call a .ASPX page. That approach is clunky and heavy-handed - but at least .ASPX is geared toward generating full HTML, unlike .ASHX.
You might want to consider returning JSON instead of XML. It makes for smaller, faster responses over the wire, and is amazingly easy to work with, within javascript. In that case, you should consider using ASMX instead of ASHX to generate the JSON, since it can be configured to automatically serialize your returned object as JSON. That's what I did on my project, and it was very fast and easy to develop.
Finally, I VASTLY prefer jquery and ajax to Microsoft's ajax and updatePanels. This stackoverflow thread details the reasons why.
I think delivering HTML is easier.
But I choose delivering XML to dynamically sort and filter data by using a javascript rendering function like:
function render(options) {
}
The options parameter will be an object that stores orderby parameter and hidden column names such as:
options = {orderby:"name", hidecolumns:["surname", "age"]};
I hope that helps.

Helpers are our "Custom Server Controls"

Is it my understanding that Helper methods are really the place where you can do the hard core logic that we would have done in lets say custom controls in ASP.NET? For instance I work for a .com which uses classic ASP.NET. The nature of our site is VERY complex, so we reuse and render different forms for thousands of products. Every product could have a different configuration form. We have a very complext RenderForm.cs custom server control that performs all the logic. Based on some configuration settings from a table in the DB, it says ok, for Product 1123 it reads the setup (that our users confugure form our internal admin system) and takes that and spits out the dynamic form (using literal controls and what not) to the p age.
So I'm thinking MVC now. Yea yea, it's all done in the View. Well partially. You're still going to have a need to have some custom logic in some .cs where it's not all embeded in your view. That would be foolish to think you're not going to have some class that will spit out some HTML..like some very hard core extensive helper methods.
So my question is, are helper methods or class where you now do your custom server control type of logic? it's basically kind of the same concept in that you need a place to put your "hard core" HTML rendering logic in some class other than a controller. Your controller is not responsible for rendering. So helper methods I guess are the so-called custom server controls in a way that I have in classic ASP.NET, figuratively speaking. I just need a yes or now on is the consensus that helper methods is the place to do all my hard core reusable logic that spits out html to the page and where I can embed custom controls into my view? Looks like it.
"Helpers are essentially static classes, designed to contain the UI logic that otherwise clutters up your UI. Think of these as UI utilities." link text
Yes, that is right on. If you do it right, you will start with the HTML helpers that MVC gives you, and you will gradually build up your own set of helpers that do even more and more for your specific project. You can get to the point where your view has only a few lines of code, which say something like, "Render entire view for Product 1123". The helpers will become your own "language" of renderers specific to your project, and you will be applying configuration, validation and everything else in a very DRY (Don-t Repeat Yourself) manner. It's phenomenal.
Update: Of course, only presentation stuff should go in your helpers. The goal is to stay DRY in your views. You still need to be careful to put into your ViewModels the things that belong in the ViewModels.
I would say "no"... or rather "only where you have to". More often than not, you can instead do the logic in the Controller (or a Service) and end up passing all the data required back to the View in ViewData. Somtimes this will mean multiple Views from one ControllerAction, less often it will mean logic in your View, and occasionally it means HtmlHelpers.
When you decide to use Helpers, it should be with the consideration that this means generated markup that won't be... well, in your markup. If you have (or later hire) a designer, that can be a problem. Or if you need to make a minor change to your layout, where do you go first? Your View or your Helpers?
[Edit] Also should ask yourself this: where is my code more easily unit tested? In a Service class which is just handing back View Data, or in a class that builds entire chunks of HTML and returns them as a String? If you're using TagBuilder, as you probably should be, then any change in the implementation of TagBuilder (even a change of whitespace handling) will break tests on a Helper without your code changing.
I'm not saying "don't use Helpers", I'm saying "don't abuse Helpers".

In ASP.net is it better to use Server Controls within the ASPX page or create them dynamically in the code behind?

I generally prefer to add controls dynamically, like table and generic html controls, to the ASPX page, rather than add them in the ASPX page and set the properties dynamically.
Which approach is considered "better practice"?
Also is using generic html controls dynamically a better practice than outputting formatted html strings to an asp:literal?
Keep them in the .aspx
Adding them dynamically leads to view state issues and they must be added in each post pack. I ran into this when building a user generated forms app. I Broke down and used the controls visibility property as a work around. That said if your eliminating view state and post back from your app these may not be issues for you.
https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx
Since in both approaches you end up with a set of code that adds controls and assigns values to their properties then the best practice is the approach that is the most readable.
Due to complex decision logic it may be better to do it all yourself on the hand for fairly static control layout where only the properties need modifying placing the control in the ASPX would be more straight-forward.

Resources