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.
Related
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.
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.
I have some classic asp code that needs converting to asp.net. So far I have tried to achieve this using datareaders and repeaters and had no luck as the menu loops through 4 different record sets, passing along the menuNid before moving to the next record.
Please can you tell me what method you would use to conver this code... i.e datareaders? dataset? etc?
Thanks
Ouch... That's some slow and repetetive code... (Excuse me for being blunt...)
You could read all the data that you need into a DataTable (using a DataSet and a SqlDataAdapter) so that you can reuse it and don't have to run a query for every level and every item in the menu. That way you can have a single database call instead of a whole lot of them, and the database calls is absolutely the bottle neck in this code.
You could use recursion to get different levels, instead of repeating the same code over and over again.
To build the elements for the menu you have several options. One is to put a PlaceHolder in the page and create a tree of controls by adding them to each others Controls collection. Another option is to simply build the HTML code yourself in a StringBuilder, and put the result in a Literal control.
well you have couple options there..
asp.net supports asp style notation, meaning <% %> etc are still supported.. and you could keep your code almost as is with some minor tweaking..
but you'd be missing out on 90% of what it has to offer. Namely the separation of markup and and code.
I recommend you familiarize your self with server control model in asp.net, and rewrite your pages to use that to get rid of all the % crap..
we can't teach you asp.net in a form answer, but server controls are the heart of the methodology there, so understanding them will bring you very close to getting a good idea in how to go about transitioning your stuff..
http://www.w3schools.com/ASPNET/aspnet_controls.asp
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.
In traditional ASP.NET Web Form applications, UserControls are a great way to encapsulate functionality so that it can be reused. However, UserControls don't fit well into the MVC model. They often make heavy use of ViewState and they blur the seperation of concerns that MVC promotes.
My question is, how do you best bundle a piece of functionality so it can be shared across MVC applications?
As an example, consider a from/to date-selector UserControl that:
allows a user to select two dates, either using a javascript overlay or by typing in day, month and year into seperate fields
can be configured to default to either today and tomorrow's dates or to dates of the developer's choosing
validates the dates that comes back from the user to ensure the from date is before the to date
exposes From and To properties that can be accessed by code-behind
How would I best build something like this in .NET MVC so that I can easily reuse it?
Note that to fully emulate User Control's functionality the MVC component would have to manage the submitted form data and validation - not just the presentation.
In general I would agree that user controls are nice in terms of encapsulating UI stuff, but I don't think too much has really changed in MVC. If I remember right re-using user controls across classic Asp.net projects was a pain and was never really the best way to truly create reusable components. Most UI toolkits that you bought for classic ASP.net didn't give you user controls, they gave you essentially server controls and javascript controls.
In your example, I would probably create or find a jquery (or ur framework of choice) plugin that did what you wanted on the client side. You could also build a C# wrapper around it similar to what Telerik did with some of the jquery UI controls. I do think that the word code-behind and even viewstate will disappear from your vocabulary the more you get into MVC.
If you look at what open source projects are out there for MVC you will get your answer in terms of what you should be doing.
The MVC Contrib app adds a lot of features by creating extension methods and helpers. Their grid control is a typical way to create a reusable component that you could use across projects
Telerik, created some extensions that wrap jquery controls and do asset management.
Finally I think if you look to the future, MVC has areas, which if I interpret it right will give you the ability to break your project apart into multiple smaller projects.
Besides what is already suggested, ASP.NET MVC v2 will have generic templated input controls, see here. You can read how other people do similar techniques, for example, here:
We have
exactly 1 method call for generating a
form element, “Html.InputFor”. As
part of that “InputFor”, it examines
an input specification, that collects
the PropertyInfo, any attributes, the
type, any modifiers called, and
selects an appropriate InputBuilder.
Call InputFor(p => p.Id) and Id is a
GUID? That creates a hidden input
element. Call InputFor(p =>
p.Customer.Address) and Address is a
complex type? That looks for a
partial with the same name of the type
Having considered the helpful answers from others, I will have a go at answering my own question.
It seems to me that the key difficulty with emulating UserControls in MVC is that they crosscut the concerns that MVC aims to seperate. The from/to date selector UserControl in my example incorporates elements of Model, View, Control and interation. UserControls' ability to bundle all this together is exactly the reason that they don't fit well into MVC.
That means that to create a psuedo-UserControl in MVC requires four seperate pieces:
A Model class - in this case an Interval class or similar
A PartialView that knows how to render the Model to HTML
A jQuery script to layer interactivity on top of the PartialView's HTML
A ModelBinder that can deserialise postdata into an instance of the Model class.
The ModelBinder is important because it deals with data coming back from the user. Without it, every Controller that wanted to display a to/from date selector in any of its Views would have to know how to assemble the six postdata fields - and how to cope if they were invalid or some were missing.
Two ways that I can think of. A partial view though this doesn't really transfer well from app to app because you are moving around ascx files. Not a big pain but not my flavour.
I prefer to use WebControls. They are super easy in mvc and all you need to do is reference the library in the project and possibly in your config file and there you go.
I think some of the answers have missed out on the postback functionality of controls. One way you could handle that is to pass any generic information via ViewData when rendering your partial view. That could then post back to its own control, which in turn could redirect to the UrlReferrer.
Its a little messy and use of UrlReferrer poses a security risk. But it is one way around the problem
You can create a jQuery plugin.
As user-controls provided in ASP.NET Webforms, MVC provide a lot of ways to make the controls and code that can be reused in other app.
Using Partials If your partial code have some C# logic and render the html using Razor/aspx code then it's bst to maintain them in razor file.
Write JavaScript Functionality as plugin If you maintain your code and write it as better as it can be used in other app then it would be a huge advantage for you. Next time when you work on other app just open this solution copy it and modify it. Write JavaScript code that can be used as plugin maybe take some more brainstorming.
Write Code As a Separate C# library If some code is too common for every app you make.for example you write a member authentication system or some global function (C#) that are used in every app you made then maintain them in a separate solution so it can be used in other app you made whenever you trying to make a new app in future.