Other options for creating table in ASP.NET - asp.net

I am creating a huge html table using StringBuilder in the code behind, based on various search criterias selected by the user. The logic is complex as I have to create sub heading, nested tables etc. and it is really hard to maintain or modify. Is there a better way to deal with such kind of problems?
Thanks!!

All ASP and Html controls are encapsulated in classes. You're interested in the Table class (for ASP) and HtmlTable for the more light-weight, html-only class.
If I had to choose, I'd go for the html one, unless you want to add server-side events to the table.

A few years ago I was in the same situation. The problem included dynamic columns, subheadings, cells, everything. A typical table would be around 1000 rows and 50 columns (that's 50,000 cells!). The original implementation used a GridView and performed horribly. I rewrote the view to use a Repeater, a very light-weight looping control, with Literal controls. That reigned in a bit of the madness vs. 100% StringBuilder. I combined that with a bunch of static methods which returned string representations for standard html bits (kind of like ASP.NET MVC's "html helpers"), as well as keeping the object model completely isolated. It was all very fast (I forget, but I think the way the Repeater and Literal controls are rendered is directly to the response stream, so performance was comparable to StringBuilder, perhaps even better).
Even the above will be complex, and is akin to your own approach. But the key to maintaining sanity is to keep the different pieces separate (object model, html generation, and dynamic binding). It's almost like building your own ad-hoc framework. But for serious jobs like this, you need to get nitty-gritty when confined to web browsers.

There's always the built in native ASP.NET Table control
http://www.w3schools.com/aspnet/control_table.asp

GridView, ListView, DataList, Table e&.

Related

ASp.Net GridView Updating using a stored procedure

I've read tons of sites on this. There are many "Examples" if you call some code with no explanation of how it was generated (design view vs typed) an example or just want to use simple select and update statements.
I have a Gridview. I am populating it using code from a stored proc. Now I want to edit the data. I have nothing set in the properties of the Gridview through design view (datasource, columns, etc.) My question is, how can I set this to allow editing and use a SP to send it back to the database?
Do I have to now manually create columns with code since I chose to not set properties in the design view?
Is it better to set the properties in design view and go that route? I started that way, but had problems when it came to updating with a SP.
I guess the whole do it in the designer vs do it in code thing has me confused.
I started adding RowEdit, RowCommand, etc. to the html and c#, but still don't see the EDIT/CANCEL on the webpage when I run it.
Learn to use the ObjectDataSource. It gives you maximum freedom of what way of storing the data you use - you delegate the select, update and delete to an external class where you just write your code which uses ado, linq, hibernate, a webservice or just anything.
Coding your views directly against fixed database structure would hurt you sooner or later.

Separate ASP.NET MVC View object for each Model CRUD operation?

Most MVC tutorials I've been reading seem to create 4 View objects for each Model. For example, if my Model is "Foo", there seem to be 4 .cshtml files: Foo/Create, Foo/Delete, Foo/Details, and Foo/Edit. Using the VisualStudio "scaffolding" helper does this as well.
Is this really considered MVC best-practice? It just feels wrong to have 4 classes that are 80-90% identical to each other. When I add a new field to Foo, I need to edit all 4 .cshtml files. This sort of dual-maintenance (quad-maintenance?) just makes my OO skin crawl.
Please tell me: is there an expected/accepted best-practice which handles this differently? Or, if this really IS accepted best-practice, tell me why the quad-maintance shouldn't make me squirm.
I'm a reasonably skilled veteran of ASP.NET / c# / OO Design, but pretty new to MVC; so apologies if this is a noob question. Thanks in advance for your help!
Edit: thanks for all the replies! I marked the most thorough one as the answer, but upvoted all that were helpful.
You'll probably need between two and four different views:
List (for viewing many things)
View (for viewing a single thing. Might not be necessary, if it's OK to use Edit as View, or if List has room to show all properties)
Create
Edit (can be the same as create, if you code cleverly)
Thus, if your model doesn't have too many properties to show them all in a table, and if you're OK with not having a static, non-editable view for just examining, you can get well away with just List and Edit, and scrap the other two.
However, this doesn't solve your problem of double (or triple) maintenance if you update your model. There's other magic for that ;)
In ASP.NET MVC 3, there are extensions on HtmlHelper that let you do Html.DisplayForModel() and Html.EditorForModel(). These use predefined templates to nest themselves into your object and draw up display/edit fields for all public properites. If you pass DisplayForModel an IEnumerable<Foo>, it will create a table with column headers that are the property names of Foo (using the DisplayName attribute information if you supplied it) and where each row represent one Foo instance. If you give EditorForModel a Foo, it will create a <label> and an <input> for each public property on Foo.
All of the templates used by these powerful extension methods can be replaced by you, if you're not happy with the defaults. This can be done either on the level of Foo, in which case you'd be back in your double-maintenance scenario, or on lower levels (such as string or DateTime) to affect all editor/display fields generated with the templates.
For more information on exactly how this works, google "ASP.NET MVC 3 editor templates" and read a couple of tutorials. They'll explain the details much better than I could.
The views that ASP.NET MVC create for you don't necessarily need to be the views that you use in production. I found those just to be handy while developing quick prototypes or to test the database CRUD operations. Feel free to create whatever view(s) you would like to handle the operations.
I would generally just have 1 or 2 views to handle the basic operations and not use the built in views that are generated. For example, 1 view for adding, editing, or details and 1 view to show a list of objects.
It all depends on your application.
If you have a single item, you don't need a List view. If you can't edit it, then you don't need an edit view. Create and Edit can often be the same view, unless there are special things you need to do in one, but not the other.
In other words, use as many views as you need. There's no hard and fast rule here. The scaffolding is just there to help you on your way. Many kinds of apps will work just fine using the scaffolding, and won't require advanced HTML or Javascript.
Why would you want multiple views? Well, let's take the display and edit functions. You could create one view, in which you use if statements to determine the edit mode of the view, however this will complicated the view logic and views should be as simple as possible.
The reason to create seperate views is that its easier to maintain than one gigantic view with tons of conditional logic in it.
You can use exactly the same view when you are performing [HttpGet]. Given that you pass a proper ViewModel to this view, it will populate with appropriate data every time whether you are loading create, update, or delete Action.
The problem becomes apparent when you try to post that data to a specific Action.
Naturally View should have only one form, which will be used for posting data. When you declare this form, you specify which exactly Action to use for Post.
Having 3 different Submit buttons in that form will not make a difference since all of them will post the same form to the same Action.
You could do some javascript tweaking on OnClick event for these buttons to change Action to which data is posted, but this definitively would not be best practice.
Buttom line: having 4 different views for each of the CRUD actions is the best practice for MVC.
I tend to create the following for an object's CRUD ops:
index
_form (partial)
new
update
delete
view
As the same form is shared between new and update, there is very little difference between the two. It really depends on how much you want the variation to be, honestly.
As for delete, this is optional. I like to have a view in case javascript is disabled.
edit:
You mention view models and the guy above posted a long, convoluted (no offense) VM code sample.
Personally, I hate classes written to basically mirror domain objects and are only used to "move" data. I hate VMs. I hate DTOs. I hate everything that makes me have to write more code than is necessary.
I guess I've drank the coolaid of other frameworks (rails, sinatra, node.js) to the point where I can't stomach the idea of tossing DRY to the wind.
I personally say skip um.
Edit2 I forgot list..

How to build flexible web forms in ASP.NET

I'm using asp.net and I need to build an application where we can easily create forms without recreating the database, and preferably without changing the create/read/update/delete queries. The goal is to allow customers to create their own forms with dropdowns, textboxes, checkboxes, even many-to-one relationship to another simple form (that's stretching it). The user does not have to be able to create the forms themselves, but I don't want to be adding tables, fields, queries, web page, etc. each time a new form is requested/modified.
2 questions:
1) How do I structure a flexible database to do this (in SQL Server)? I can think of two ways: a) Create a table for each datatype (int, varchar(x), smalldatetime, bit, etc). This would be very difficult to create the adequate queries. b) Create the form table with lots of extra fields and various datatypes in case the user needs 5 integers or 5 date fields. This seems the easiest, but is probably pretty inefficient use of space.
2) How do I build the forms? I thought about creating an xml sheet that had the validations, data type, control to display, etc. as a list. Then I would parse through the xml to build the form on the fly. Probably using css to do the layout (that would have to be manual, which is ok).
Is there a better/best way? Is there something out there that I could look at to get ideas? Any help is much appreciated.
This sounds like a potential candidate for an InfoPath solution. At first blush, it will do most/all of what you are asking.
This article gives a brief overview of creating an InfoPath form that is based on a SQL data source.
http://office.microsoft.com/en-us/infopath-help/design-a-form-template-based-on-a-microsoft-sql-server-database-HP010086639.aspx
I have built a completely custom solution like you are describing, and if I ever did it again I would probably opt for either 1) a third-party product or 2) less functionality. You can spend 90% of your time working on 10% of the feature set.
EDIT: reread your questions and here is additional feedback.
1 - Flexible data structure: A couple things to keep in mind are performance and the ability to write reports against the data. The more generic the data structure, the harder these will be to achieve (again, speaking from experience).
Somewhat contrary to both performance and report-readiness, Microsoft SharePoint uses XML fragments/documents in generic tables for maximum flexibility. I can't argue with the features of SharePoint, so this does get the job done and greatly simplifies the data structure. XML will perform well when done correctly, but most people will find it more difficult to write queries against XML. Even though XML is a "first class citizen" to SQL Server, it may or may not perform as well as an optimized table structure.
2 - Forms: I have implemented custom forms using XML transformed by XSLT. XML is often a good choice for storing form structure; XSLT is a monster unto itself, but it is very powerful. For what it's worth, InfoPath stores its form structure as XML.
I've also implemented dynamic forms using custom controls in .Net. This is a very object-oriented approach, but (depending on the complexity of the UI) can require a significant amount of code.
Lastly (again using SharePoint as an example), Microsoft implemented horrendously complicated XML list/form definitions in SharePoint 2007. The complexity defeats many of the benefits. In other words, if you go the XML route, make your structures clean and simple or you will have a maintenance nightmare on your hands.
EDIT #2: In reference to Scott's question below, here's a high-level data structure that will avoid duplicated data and doesn't rely on XML for the majority of the form definition.
Caveat: I just put this design together in SQL Management Studio...I only spent 10 minutes on it; developing a flexible form system is not a trivial task, so this is an over-simplification. It does not address the storage of user-entered data, just the definition of the form.
The tables:
Form - top-level form table which contains (as you would guess) the collection of fields that comprise the form.
Field - generic fields that could be reused across forms. For example, you don't want 50 different "Last Name" fields for 50 different forms. Note the "DataTypeId" column. You could store any type you wanted in this column, like "number, "free text", even a value that indicates the user should pick from a list.
FormField - allows a form to contain 0-many fields in its definition. You could even extend this table to indicate that the user can ADD as many of this field as they need.
Constraint - basically a lookup table that defines a constraint type (maybe it's max length, max occurrences, required, etc.)
FormFieldConstraint - relates a constraint to a particular instance of a form field. This table combines a specific form with a specific field with a specific constraint. Note the metadata column; this potentially would be a good use for XML to store the specifics of the constraint.
Essentially, I suggest building a normalized database with few or no null values and no duplicated data. A structure as I've described would get you on the path to that goal.
I think if you need truly dynamic forms saved into a database, you'd have to create a sort of "dictionary" data table.
For example...
UserForms
---------
FormID
FieldName
FieldValue
FormID relates back to the parent form (so you can aggregate all of the fields for one form. FieldName is the name of the text field entered from. FieldValue is the value entered/selected for that field.
Obviously this isn't a perfect solution. You could have issues typing your data dynamically, but I leave the implementation of that up to you.
Anyways, hopefully this gives you somewhere to start thinking about how you'd like to accomplish things. Good luck!
P.S. I've found using webforms with .NET to be a total pain when doing dynamic form generation. In the instances I had to do it, I ditched it almost entirely and used native HTML elements. Then rewired my form by using the necessary values from Request. Probably not a perfect solution either, but it worked the best for me.
We created a forms system like the one you're describing with a schema very similar to the one at the end of Tim's post. It has been pretty complicated, and we really had to wrestle with the standard WebForms controls like the DetailsView and GridView to make them be able to perform CRUD operations on groups of answers. They're used to binding straight to properties on an object, and we're forcing them to look up a field ID in a dictionary first. They don't like it. You may want to consider using MVC.
One tricky question is how to store the answers. We ended up using a table that's keyed on FieldId, InstanceId (for example, if 10 people are filling out your form, there are 10 instances), and RowNumber (because we support multi-row forms for things like employment history). Instead of doing it this way, I would recommend making your AnswerRow a first-class concept with its own table tied to an Instance, and having the answers be linked to the AnswerRow and Field.
In order to support different value types, we had to create multiple answer fields on our answer table (AnswerChar, AnswerDate, AnswerInt, AnswerDecimal). Each of these maps to one or more Field Types (Date, Time, Number, etc.). Each Field Type has its own logic to represent the value in the UI, and put the value into the appropriate property on our answer objects.
All in all, it's been a lot of work. It's worth it for us, since this is the crux of the product, but you will definitely want to keep the cost in mind before embarking on a project like this.

ASP.NET and JavaScript dynamic show/hide based on other form fields

I seem to keep running into these complex show/hide scenarios in ASP.NET web forms where the logic goes "if Field A equals blah, and Field B equals blahblah, then Field C is shown/hidden/validated/whatever." Before I run off and start building custom validators and custom controls so I can more easily manage it in markup or backend code, are there any libraries or simpler solutions I'm missing out there in the wild? jQuery makes the job easier, but I get the feeling I could abstract a lot of what I'm wrangling with out into a more elegant solution.
All of the controls that are dependent on each other or could trigger events are my own custom controls already, so I get the feeling I could start writing a small framework to handle it like so:
<my:DynamicShowHide runat="server">
<PrerequisiteFields>
<PrerequisiteField ControlId="FieldA" Value="blah" />
<PrerequisiteField ControlId="FieldB" Value="blahblah" />
</PrerequisiteFields>
<DependentFields>
<DependentField ControlId="FieldC" />
</DependentFields>
</my:DynamicShowHide>
...that way if the Prerequisite values were both evaluated as true, the DependentField would show, and hide if not.
It seems (and feels) like I'm overengineering but I run into insanely large and complex decision trees like this more and more often. Anyone know of a better way or an existing library that does something along these lines?
out of interest, in which particular instances do the use of decision trees most prominently arise?
For instance, I am guessing it is in most cases with dynamic data (data retrieved from a DB). And say the common usage for it would be in forms (or questionnaires) - hard to say as you have supplied examples of the usage of decsiion trees.
If these are the cases, then would it not be nice to handle all the stuff in the DB and populate the controls in the browser dynamically? You can set all the dependantUpon, and ansewrLeadsTo in the database, and the possible answers, and type of input control to generate, and it would lead to a much cleaner solution.
Granted the initial setup would be hard, but in the longterm, consider flexibility and maintenacne, and it should be okay.

asp.net gridview vs writing innerhtml

Are there any performance benefits to me not using the gridview in asp.net for simple tables querying from a stored procedure and instead writing the html in server code myself. I'm sure my code would certainly be more concise in output.
I am going to propose an alternate solution. If you don't need any of the features of a GridView, why not use a repeater.
A repeater keeps it simple for implementation, but also allows you to have full control over the generated source. Without the issue of string concatentation preformance.
I've found marginal performance improvements with repeaters over GridViews.
No, there are no performance benefits with using a GridView. In general, the GridView is going to decrease a little bit of performance due to the fact that items are written into the ViewState,and additional HTML is generated. The benefits you DO get from the GridView include command events and arguments that can be easily consumed or created, a DataKey "property bag" that allows you to track critical fields in a large result set, as well as many other things. I will add this caveat that I've used GridViews on even very simple result set returns and have not seen any significant performance problems.
If you are simply doing some output from a table query, and not worrying about doing too much interaction with the data from the results itself, "rolling your own" would provide a great solution.
Well, of course it depends on your implementation. You could almost certainly build something that runs faster than the stock gridview.
The problem is, how would you know? The default system for string concatenation in .Net is by it's nature very slow, so it would be easy to accidentally build something that is much slower than the stock gridview. You could of course test things out, but the development time investment is likely to outweigh an server performance gains.
There's an additional possibility here that exists between using a GridView and using a StringBuilder to generate HTML. I'm talking about using the ASP Table class. I have seen impressive speed benefits on using them over a standard GridView when all I'm doing is spitting out data. As an added bonus, I can add a button (or linkbutton) to my output and wire it up with an event handler and still get the functionality of a GridView in that regard.
You'd use it thus:
Dim tab As New Table
For Each row In DataTable.Rows
Dim tabRow as New TableRow
For Each col In row.Columns
dim tabCol as New TableColumn
tabCol .Text = row(col)
tabRow.Controls.Add(tabCol )
Next
tab.Rows.Add(tabRow)
Next
Page.Controls.Add(tab)

Resources