Critique this strategy - asp.net

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.

Related

Get value form elements inside div with only ASP.NET

I'm newbie in ASP.NET and i think that my question is quite simple, but I'm not getting success in my searches through google or even stackoverflow.
I have a asp.net method (vb.net) that loads a entire html page inside a div.
Doing searches, i discovered that it can be like this:
On .aspx page:
<div id="content"></div>
On .vb codebehind:
Private sub LoadContent()
content.InnerHtml = MyDLL.LoadFromDatabase.Value.ToString()
End Sub
So, nothing special until here.
But, if consider that the html code loaded from database has form elements like <input id="name" type="text">, my problem starts...
On page postback these don't keep the values as <asp:TextBox> created natively on code, does.
And the other thing that I want is a way to retrieve the value from them to work on codebehind, like: myvar = content.Controls("name").Value
At least, is there a way to solve my problem?
Sorry for my bad english, and thanks so much.
CRice is right. If you want the viewstate to persist through postback you need to create the controls server-side.
Careful though: I've had bad experience with dynamically created controls on Asp.Net, specifically when trying to bind events to them. Not only would you have to use delegates and events (a hard topic for a newbie), also when I tried it a few years ago I just couldn't get it to work, no matter what.
If you're going for dynamic created controls, make sure it's worth the effort, because it WILL be an effort, now and in the future when you would like to maintain and add expand. A rule of thumb is that dynamic mechanisms are always harder to maintain than static ones, but they provide more flexibility.
Having that said, if you're still going for dynamic html loading, be aware that better solutions exist, though they require different architectures: client side frameworks (best is angluar.js) provide dynamic loading of "modules" (and much more), which is what you want. On the server side, asp.net MVC with its Razor view engine, partial views etc., is better suited for dynamic html generation.
Back to your original question,are you sure you need a full postback? What about a nice neat Ajax call to a web service? Can get the job done in many cases without reloading the whole page. I guess using jquery's $.ajax syntax and creating a simple .asmx web service will be easiest for you.
Last but not least, why use vb.net instead of c#? It sucks man. Give it up while you still can.

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.

aspx ashx mash-up

I'm retro-fitting a .aspx page with AJAX functionality (using VB, not C#). The codebehind populates the page with data pulled from a web-service. The page has two panels that are populted (with different data, of course) in this way. On a full page refresh, one or both panels might need to be populated. But populating Panel 2 can take a long time, and I need to be able to update panel 1 without refreshing Panel 2. Hence the need for AJAX (right?)
The solution I've come up with still has the old .aspx page with .aspx.vb codebehind, but introduces a Generic Handler (.ashx) page into the mix. Those first two components do the work on the user's first visit or on a full page refresh, but when AJAX is invoked, the request is handled by the .ashx page.
First question: Is this sound architecture? I haven't found a situation online quite like mine. Originally, I wanted to make the .aspx page into the AJAX handler by having the codebehind implement IHttpRequest, and then providing "ProcessRequest" and "IsReusable" methods, but I found I couldn't separate a regular visit to the page from an AJAX request, so my AJAX handlers took over even on the first visit to the page. Second question: Am I right to think that this approach (making the .aspx page do double-duty as the AJAX handler) will never work? Is it impossible to tell whether we're getting a full-page request or a partial-page (AJAX) request?
If the architecture is good, then I need to dynamically generate a lot of HTML in the .ashx file, right? If that is right, should I send HTML back to the client, or should I encode it in some way? I've heard of JSON encryption, but haven't figured out how to use it yet. So, Third question: Is "context.Response.Write" the only pipeline for sending data back to the client? And, if so, should I send back HTML or some kind of JSON-encoded objects?
Thanks in advance.
It sounds as if the page requires some AJAX functionality added to the UI.
Suggest using an UpdatePanel for each web form element that needs to have AJAXy refresh
functionality. That'll save you from having to refactor a bunch of code, and introduce a whole lot of HTML creation on your .ashx.
It'll be more maintainable over the long run, and require a shorter development cycle.
As pointed out by others, UpdatePanel would be a easier way - but you need to use multiple update panels with UpdateMode property set as conditional. Then you can trigger the update-panel refresh using any button on the page (see AsyncPostBackTrigger) or even using java-script (see this & this). On the server side, you may decide what has triggered the partial post-back and act accordingly by bypassing certain code if not needed.
You can also go with your approach - trick here is to capture the page output using HttpServerUtility.Execute in your ashx and write it back into the response (see this article where this trick has been used to capture user control output). Only limitation with this approach is that you can only simulate GET requests to your page and so you may have to change your page to accept parameters via query string. Personally, I will suggest that you create a user control that accept parameters via method/properties and will generate necessary output and then use the control on your page and in ashx (by dynmaically loading it in a temperory page - see this article).
EDIT: I am using jquery to illustrate how to do it from grid-row-view.
$(document).ready(function() {
$("tr.ajax-grid-row").click(function() {
$("#hidden-field-id").val($(this).find(".row-id").val()); // fill hidden filed
$("#hidden-button-id").click(); // simulate button click
});
});
You can place above script in the head element in markup - it is assuming that you have decorated each grid-row-view with css class "ajax-grid-row" and each row will have hidden field decorated with css class "row-id" to store row identifier or the value that you want to pass to server for that row. You can also use cell (but then you need to use innerHTML to get the value per row). "hidden-field-id" and "hidden-button-id" are client ids for hidden field and submit button - you should use Control.ClientID to get actual control ids if those are server controls.
JSON is not for that purpose, it is to pass objects serialized with a nice light weight notation, is you need to stream dinamically generated html using ashx, response.Write is what you have. You may want to take a look at MVC
Or you could use jquery if it's just html, the simpliest would be the load function, or you can look into Ajax with jquery. Since the ashx can be served as any resource it can be used in the load function.
I agree with #p.campbell and #R0MANARMY here. UpdatePanel could be the easiest approach here.
But then like me, if you don't want to go the UpdatePanel route, I don't see anything wrong with your approach. However, generating the html dynamically (entirely) at the back end is not a route I'll personally prefer (for the maintainence reasons). I'd rather prefer implementing a solution that will keep the design separate from the data.

refresh grid without page post back, please advise

I am doing some grid work just like a stock exchange application which will have good data volume and page should be automatically refresh after some mentioned time say 1 min or 30 sec without being post back.
What is best way to do this ? Should I use grid with ajax or grid with ajax and web service should be used ? If possible please refer me some article or link on implementation of your suggestion.
You can use an UpdatePanel (place the grid inside the panel) and maybe have a JavaScript timer to update the panel periodically.
Alternatively you can have a straight HTML table and periodically call a webservice and update the table from the client side. I think you would get slightly better performance but there is a bit more work involved.
A webservice call from JavaScript will not cause a postback. When calling a webservice you might get better performance because you are only getting data instead of formatted HTML. However, you will probably return the data in XML or Json format, so there will be an overhead (Json will be better in that respect).
If you know that only a small portion of values are going to change between two refreshes, then you will get better performance by only returning the values that have changed.
If you're not very experienced with JavaScript then I would suggest that you use a library such as jQuery. You may read the following resources for implementation details:
Calling an ASP.NET webservice with jQuery
Updating an HTML table from Json data using jQuery
Depending how experienced you are with webservices, Json and jQuery, it may not be an easy task. The UpdatePanel option is definitely easier to implement.

Facebook Wall functionality using ASP.Net

I want to create something similiar to a facebook wall on my social site. I want to store the posts in an sql database and that should be rather simple. What I am looking for is a good way to display the posts? I guess I don't even really know where to start, as I can only think of using a loop to display asp:textboxes. Which obviously is not correct.
I want there to be multiple posts displayed on the page, which should include:
the user who posted,
the text posted,
the date posted,
and if I want to get crazy...a means of deleting/editing the post.
I really have no idea of how to implement this concept, so any ideas would help greatly.
To get started, view this article from asp.net on the Repeater control, or this great article.
The Repeater control lets you databind to a list of objects, and then define one template for how that object should be displayed. Then, ASP.NET will handle showing it as many times as necessary. You can write the code-behind for dealing with delete and edit as if there were only one instance on the page.
go ahead with jquery, use a lot of ajax. for the mark up, use a repeater control with all clean html mark up (instead of server side controls which would generate a lot of unnecessary mark up quickly creating performance issues)
only populate x number of items on initial load, and then using jquery pull data as required based on user action. you can serve this data via json, decode json on client side using jquery and perform a loop which converts this json into appropriate html and injects it into the correct html element
should be simple ;-)
ASP.NET gives you lots of ways to do this. A Repeater, DataGrid, GridView are the first that come to mind. If you'd rather use ASP.NET MVC, there's always the good old foreach loop.
Additionally, check out ListView too.

Resources