JQuery and ASP.NET Web Forms

2019-08-27 18:23发布

问题:

I am creating a ASP.NET Web Form application where I am trying to use some nice jQuery functionality and flashyness. The current part of the application I have consists of two jQuery UI tabs; a search tab and a results tab. When the user performs a search from the search page, the results tab will be selected and the results will be displayed in this tab. I need to get the results into a gridview. Now this is where the issue starts to come in:

The easiest way to get the search results is to allow the search click to perform the postback where I can then format the datasource with the parameters from the input fields and let the datagrid take care of itself and data bind and show the results. The thing is, this really doesn't look that great (due to the whole post back and such) as well as starts to cause some issues with using javascript/jQuery to take care of tab switching and all that portion because the postback reinitializes everything from the jQuery UI (i.e. the jQuery UI tabs). So in short, the postback allows for easy binding of the input for the search and getting the results, but makes the page and its behavior all wonky.

I was wondering if there is a standard way to do this type of mixing jQuery/javascript/AJAX all together within web formto get the functionality of things like the gridview and such. I am wondering if there are some good tutorials, or even just a direction on solving this issue.

I hope all this made sense, and thank you all for your help.

回答1:

I don't think this is a standard, but here is the pattern I use:

First of all, I use Page Methods for ASP.Net to get hooked back up to the server. In this case it would be something like this:

PageMethods.Search(searchValue, onSearchComplete);

That calls a static page method in the page, like this:

public static void Search(string searchValue)
...

Inside that procedure, I create an instance of a user control which contains the gridview, and invoke a method on that control, passing the searchValue:

var searchControl = (SearchControl)new SearchControl().LoadControl("/controls/SearchControl.ascx");

searchControl.Search();

var stringBuilder = new StringBuilder();
using (var textWriter = new StringWriter(stringBuilder))
{
      var htmlWriter = new HtmlTextWriter(textWriter);

      searchControl.RenderControl(htmlWriter);
      return stringBuilder.ToString();
}

This is all going to end up as the result argument to the handler you specified in the initial call (onSearchComplete) in this example. You can do whatever you want with the markup, including slapping it into a div, or alerting it for debugging.