During ASP.Net development i am often unsure weather i should be performing some functionality using an ajax request vs handling it all on the client with JavaScript. I often will want to use Jquery ajax functions in order to speed development up and improve maintainability even though i can achieve the same result without contacting the server.
Here is one example. In my MVC view i need to update a partial view in response to a button click. Here is a simplified version of my partial view
#foreach (Requestbox.Code.XmlContentField xmlControl in Model.RequestContentControls)
{
if (Model.IsInEditMode)
{
ViewContext.Writer.Write("<div class='editDiv'>
<a href='#' onclick='EditClick()'>Edit</a>
<a href='#' onclick='DeleteClick()'>Delete</a>");
}
switch (xmlControl.ControlType)
{
case "TextBoxField":
<div class="clearfix">
#Html.DevExpress().Label(settings => {
settings.Name = xmlControl.FieldName + "Label";
settings.AssociatedControlName = xmlControl.FieldName + "TextBox";
settings.Text = xmlControl.LabelText;
}).GetHtml()
<div class="input">
#Html.DevExpress().TextBox(settings => {
settings.Name = xmlControl.FieldName + "TextBox";
MvcExtensionHelpers.SetTextBoxSettings(settings);
settings.ControlStyle.CssClass += " full-width";
}).GetHtml()
</div>
</div>
break;
case "Header":
string header = string.Format("<{0}>{1}</{0}>", xmlControl.HeaderType,xmlControl.Value);
#Html.Raw(header)
break;
}
if (Model.IsInEditMode)
{
ViewContext.Writer.Write("</div>");
}
}
When the Edit button is clicked i need to wrap each of my sections in a div and add 2 anchor elements with onclick functions inside. I can do this by using an ajax post request and setting the Model with "IsInEditMode to true" here is the code i could call, which replaces the current partial view with the new one.
function EnableEditClick() {
$.post(rootDir + "Admin/EditClick",null,
function(partialViewResult){
$("#refTable").html(partialViewResult);
});
}
Here is the Action that could handle the ajax request
public ActionResult EditClick()
{
MyModel model = new MyModel();
model.IsInEditMode = true;
return PartialView("CustomRequest", model);
}
This is one solution, another would be to handle this all on the client by using jquery to select each of my elements that are needed and to insert the anchor elements directly. I would also be able to take some code out of the view. So something like this (Haven't tested this code but i hope you get the idea)
function EditClick()
{
var elements = $('.myTable .clearfix')
elemtns.append(' <a href='#' onclick='EditClick()'>Edit</a>
<a href='#' onclick='DeleteClick()'>Delete</a>');
}
I am torn on which will be better maintainability wise, as with the ajax way i don't have to write html in JavaScript pages and i think it will be clearer and more readable when revisting the code. However i am then using a unnecessary request to the server when i could it handle all on the client.
So my questions is should i always be doing everything on the client if possible even at the result of maintainability. Any feedback on my example is much appreciated as well.
I recommend you to use AJAX for operations, which require some background calculations on the server or to retrieve some DB data from the server. For GUI generation I would use JS, as it is quite quick, thanks to V8.
If you need to generate GUI by embedding some server data into it and this page has complex layout, I would use server side template engine.
In the example you've given, I would recommend the JS approach to control the availability of the edit and delete buttons. Or possibly a combination of the two.
When you make an Ajax call it creates a background request that causes some HTTP traffic. Unless there's some processing needed on the server to fulfil the request, then there is not much use sending that request to the server.
From looking at your code then the action you want to perform is to add two anchors to the page. This can be done easily with JS. You could even combine the two by including a partial view on your page that contains the elements you wish to include, wrapped in some markup to hide them.
You could create a partial view with the button markup.
<a href='#' onclick='EditClick()'>Edit</a>
<a href='#' onclick='DeleteClick()'>Delete</a>
And then include in your view.
<div id="buttons" style="display: none;">
#Html.Partial("_ButtonView")
</div>
Your JS would become.
function EditClick()
{
$("#buttons").toggle("display");
}
Check this JSFiddle for an example of what I mean.
In the context of this question, I would consider using an Ajax request for the actual edit action that returns a Json result with the action output. This would end up with something like.
$.ajax({ // ajax call starts
url: "YourArea/YourController/EditClick",
data: {"your data"},
dataType: 'json',
success: function(data) {
//handle json response
}
});
This Ajax request would call the controller code.
public JsonResult EditClick()
{
var myResult = Helper.Edit();
return Json(new { result = myResult });
}
Conclusion: If an event/action only affects what the user can see on the UI (i.e. controlling visibility and initiating animations) then you would probably only want to use JS/jQuery. If there's something more happening like server processing or fetching data from DB required then consider using Ajax.
In your example it seemed like the choice was between adding the elements dynamically to the page with JS or executing an Controller method via Ajax to get the elements as a partial view. I hope this answer provides a good solution for you.
Related
I want to pass js array from View via post to controller, then process the data and return the data to another view.
Problems that I've experienced:
-can't use ajax to post data, because I won't be able to return another view
When you use $.post it calls your action then gets back a bunch of
HTML. And then you do nothing with it, so the browser just throws it
away. If you want to just go to the new page, do a regular post and
don't use ajax. Ajax is more for if you need to call your server to
get some information to UPDATE the current page, not go to a new one.
(i guess it's the same for $http.post as well?)
-can't use regular post (#Html.Beginform) I think becaue I won't be able to pass the js array?
How should I deal with it?
If you absolutely want to do a normal form submit(non-ajax) with data in your js variable, you may build some form input elements for the data you have in your js variable and then you can use javascript to submit this form. As long as the name of the elements match with your action method parameter, model binding will work.
Here is a simple example to send a list of strings on a button click event, using jQuery.
$(function() {
var flags = ["aa", "bb", "cc"];
var targetUrl="#Url.Action("Summary","Home")";
$("#SubmitButton").click(function(e) {
//First build a form element and set the action attribute value
var $f = $("<form></form>").attr("action",targetUrl).attr("method","post");
//Loop throug the string and create an input element for each item
$.each(flags, function(a, b) {
var $el = $("<input type='hidden' name='flagsChecked' />").attr("value",b);
//Add the input element to the form
$f.append($el);
});
//Add the form to the page and submit the form
$f.appendTo("body").submit();
});
});
and in your http post action method , you can return a view.
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
return View("Summary");
}
If your code is to udpate some data, i strongly suggest you to follow the P-R-G pattern and return a redirect response.
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
return RedirectToAction("Summary");
}
You can pass multiple values in a regular post with #Html.BeginForm.
The values will then be encoded like that: key=foo&key=bar&key=baz.
Check out the following post if you need more information: https://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
Pass js array to mvc controller
Well you have two separate issues. First you have to bind either a application/x-www-form-urlencoded or multipart/form-data or json to your object/array.
Phil Haacked - Model Binding To A List
Excerpt:
start
<form method="post" action="/Home/UpdateInts">
<input type="text" name="ints" value="1" />
<input type="text" name="ints" value="4" />
<input type="text" name="ints" value="2" />
<input type="text" name="ints" value="8" />
<input type="submit" />
</form>
you were to take fiddler and look at what data actually gets posted when clicking the submit button, you’d see the following.
ints=1&ints=4&ints=2&ints=8
The default model binder sees all these name/value pairs with the same name and converts that to a collection with the key ints, which is then matched up with the ints parameter to your action method. Pretty simple!
end
then return another view
Well you have pretty much two options.
First, you use a standard <form> element with a url and a way to submit the form (submit button, jQuery etc). Pros: its been around litteraly forever and very simple to use. Cons: if there is network outage or something, your user experience is very poor (browser, url cannot be found, so I hit refresh do I resubmit... I don't know.. etc)
Second, you use an Ajax request and send the data. When the response is successful, you window.location your user to the next screen. Pros: fantastic user experience, if the network fails, you can retry or give the user a way to retry. Cons: definitely more work to implement.
Does it have to be a post?
one javascript example of doing this with a get request:
var url = "/Controller/Action?";
var myArray = {id1: 100, id2: 200, "id3": 300};
for (var key in myArray) {
url += key+"="+myArray[key] + "&"
}
window.top.location.href = url
otherwise just make a post:
var form = $('<form></form>');
var url = "/Controller/Action";
form.attr("method", "post");
form.attr("action", url);
var myArray = {id1: 100, id2: 200, "id3": 300};
for (var key in myArray) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", myArray[key]);
form.append(field);
});
$(document.body).append(form);
form.submit();
Basically I am looking for a reliable log out mechanism when the user closes his tab. This includes calling some server code and thus all client side only mechanisms like deleting the cookie wont work for me.
On the internet you mostly find the approach to intercept the window.unload function and then place some code in there. I know there is the possibility to filter out normal navigation requests from other events that might trigger window.unload, but I generally don't like this approach, as I have to make some sort of synchronous AJAX call in order to reliable execute some custom logout code on the server, which is definitely not the best way of achieving what I want.
There is the second approach of implementing a Heartbeat function to periodically check if the client responds. I do think this is the best approach for me / my scenario, but I am actually struggling with the implementation with ASP.NET MVC.
How would I approach this in ASP.NET MVC? I already thought of SignalR, but it's actually not directly possible to access session information within the SignalR context.
It is easy to find some fancy implementations of this (see, for instance, this question).
For a basic heartbeat implementation you will need three files: the HTML (the website page sending the beats), the controller (receiving the beats) and the JavaScript file (with your heartbeat function). You may include the JavaScript code in the HTML file, but it's better practice to keep it separated.
Here you have the exact contents of my working example:
HTML file (Heart.cshtml)
Note that you need to include both the JavaScript file and jQuery. #Url.Action("ReceiveHeartbeat", "Auxiliary") gives the address to the method (ReceiveHeartbeat) in the controller (AuxiliaryController).
<head>
<script type="text/javascript" src="~/Scripts/heartBeat.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
LaunchHeartBeat('#Url.Action("ReceiveHeartbeat", "Auxiliary")');
</script>
</body>
Javascript (heartBeat.js)
Other people use setTimeout, but if you want a loop using setTimeout is cleaner. I would recommend writing two functions, using setInterval(myFunction, myInterval); (see below). You can add more stuff to the Ajax request (for instance, a success: action).
function LaunchHeartBeat(actionUrl) {
var intervalMilliseconds = 750;
setInterval(function () {
$.ajax({
type: "POST",
url: actionUrl
});
}, intervalMilliseconds);
}
Controller (AuxiliaryController.cs)
[HttpPost]
public JsonResult KeepSessionAlive()
{
// You may do stuff here
return new JsonResult { Data = "success" };
}
Edit: The alternative syntax for the Javascript file:
var actionUrl = null;
var intervalMilliseconds = 1000;
function LaunchHeartBeat(myUrl) {
actionUrl = myUrl;
setInterval(HeartBeat, intervalMilliseconds);
}
function HeartBeat() {
$.ajax({
type: "POST",
url: actionUrl
});
}
I've seen a couple of methods on how to do this. My own method that I like, except from one part, is the following:
Hijack submit-event of form
Collect the data and build a json object
var objToSend = { Property : $('#propertyField').val(), Property2 : ... };
This is the part I don't like since it's tedious to collect 25 values like this
Call $.ajax({}) and specify the url to point to an [HttpPost] enabled action somewhere
in the success: part of the ajax-query, collect the returned data (which I return as a string) and write it out where appropriate. I handle errors here as well, checking to see if the first word is "Error:" and then taking appropriate action.
I like this method apart from the collection stage. I am sure there is a better way of doing this but I'v thrown myself headlong into jquery coming from an ASP.NET WebForms-background so the whole "embrace the web" part is totally foreign to me.
You could use the serialize() method to avoid passing all the fields one by one. It will send the entire form data to the server using application/x-www-form-urlencoded content type as if it was a standard form submission:
$('#myform').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
// TODO: handle the success case
}
});
return false;
});
Another possibility is the jQuery form plugin:
$('#myform').ajaxForm(function(result) {
// TODO: handle the success case
});
Some people find it also useful to use the Ajax.BeginForm helpers to render the form:
#using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "success" }))
{
... some input fields
}
In ASP.NET MVC 3 you need to include the jquery.unobtrusive-ajax.js script which unobtrusively AJAXifies the HTML 5 data-* attributes emitted by the Ajax helper.
Allow jQuery to build your json for you. You can serialize a form which will create a data set for you to submit.
$.post("myUrl",
$("form").serialize(),
function(callback) { ... }
);
That's how I'd do it!
You also have the option of using the MVC helpers to create the post code handling code for you if you're dealing with a form e.g.
<% using (html.BeginForm()) {%>
// html for the form
<input type='submit' value='post' />
<% } %>
The transition from WebForms to MVC can be a tricky one for people has you really are dealing with the raw aspects of web programming i.e. http, html and javascript... BTW I believe this to be a good thing as I'm not a fan of the pseudo single process event model of WebForms.
Long live MVC! :)
I tend to use the "jQuery form plugin". It allows you to cleanly abstract a standard form into an AJAX form with very little effort:
http://jquery.malsup.com/form/
It also allows you to easily trap various events, failure conditions, validations etc and can convert your form to a JSON request or XML if you desire. Handles file uploads too.
I've written some basic Javascript functions and would like to learn how to enable asynchronous postbacks within a C# 4.0/ASP.net project using this JS code.
For example, I have a script that increments a number when clicked. When clicked again, the number is decremented. I basically load the number from a database, then hide one <span> and show another with the corresponding decremented number on click. This is not complicated javascript; its a simple example. Now when I click the button I want to send this increment/decrement call back to the server to update the database's number.
I realize that I can accomplish something akin to this example using the AJAX Control Toolkit's toggle button. I, however, want to know how to use my OWN javascript to create AJAX functionality.
How do I accomplish this using C# and my custom Javascript code?
I'm not opposed to using the ASP.net AJAX library, I just don't want to use a ready built control. I want to learn the process of creating my own AJAX functionality. I would presume that I will have to use an asp:UpdatePanel, but I don't know how to call C# functions from the client side.
My javascript is not jQuery, in fact I want nothing to do with jQuery until I learn more about javascript and this process.
Simple with no UpdatePanel:
First, add a Generic Handler to your project (.ashx). This will act as our Http endpoint. Our javascript will call it. We could (and probably should), use a web service endpoint but that requires processing the response and complicates the example. A handler returns plain text.
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler
{
// We'll use a static var as our "database".
// Feel free to add real database calls to the increment
// and decrement actions below.
static int TheNumber = 0;
public void ProcessRequest(HttpContext context)
{
string action = context.Request.QueryString["action"];
if (!string.IsNullOrEmpty(action))
{
if (action == "increment")
TheNumber++; //database update and fetch goes here
else if (action == "decrement")
TheNumber--; //database update and fetch goes here
}
context.Response.ContentType = "text/plain";
context.Response.Write(TheNumber);
}
public bool IsReusable { get { return false; } }
}
Next, create your web page and add the async javascript.
<%# Page Language="C#"%>
<html>
<head runat="server">
<script type="text/javascript">
// An XMLHttpRequest object is required to make HTTP requests.
// Try a couple instantiation strategies to handle different
// browser implementations.
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch (e) { }
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
alert("XMLHttpRequest not supported");
return null;
}
function callHandler(action) {
var xmlHttpReq = createXMLHttpRequest();
// We're interested in an asychronous request so we define a
// callback function to be called when the request is complete.
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
document.getElementById("<%= lbl.ClientID%>").innerHTML
= xmlHttpReq.responseText;
}
xmlHttpReq.open("GET", "Handler.ashx?action=" + action, true);
xmlHttpReq.send(null);
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<div>
The Number: <Label runat="server" id="lbl">0</Label>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="Increment"
OnClientClick="callHandler('increment');return false;" />
<asp:Button ID="Button2" runat="server" Text="Decrement"
OnClientClick="callHandler('decrement');return false;" />
</div>
</form>
</body>
</html>
The final flow is:
A web page user clicks the Increment or Decrement button which calls our javascript
Our javascript sends a request with the desired action in the querystring to Handler.ashx
Handler.ashx reads the querystring, increments or decrements its static variable, and returns the value
Our callback receives the value and updates our UI.
if your using an UpdatePanel it's very simple with a JavaScript call to __doPostBack. See here for example.
Have a look at this tutorial around AJAX
http://www.w3schools.com/Ajax/Default.Asp
It will give you an overview of using Javascript to GET and POST data using AJAX.
Hope this helps.
Here's a link on how you can incorporate ASP.NET C# with your custom Javascript code.
http://msdn.microsoft.com/en-us/library/bb386450.aspx
It also contains a sample VS 2010 project here:
http://go.microsoft.com/fwlink/?LinkId=185646
Here's generally what's going on here:
In the AjaxIScriptControl solution:
SampleTextBox.cs - takes care of rendering the script control on the page; and attachment to client javascript code (the js file)
SampleTextBox.js - takes care of client side functionality and generates Javascript object of control via prototype
Notes:
This example leverages existing
ASP.NET's built-in control (you
notice SampleTextBox inherits Textbox
and IScriptControl) but you can
render any type of HTML control if
you inherit ScriptControl class
instead.
This solution also chose to separated
the Script control code and website
code in two projects but you can
easily make it into one.
You can easily leverage another Javascript library in your JS file
In my experience so far, this is the one of the more elegant way to incorporate server side code with client side if you are to create re-useable controls for your website. You leverage server side power to do the initial rendering while provide client side capabilities through Javascript.
If you create your C# functions as WCF REST Services or older-style Script Services, then you can easily call your service methods from your JavaScript using a basic XmlHttpRequest (no jQuery or UpdatePanels needed).
Here's a quick jsFiddle I put together: http://jsfiddle.net/ndVeS/
This sample has two text boxes; you enter a value in the first one, click the button, and then that value is passed to a service (an echo service) and returned in the callback. The JavaScript code takes that value and populates the second textbox with it.
You could define a C# WCF RESTful service like this:
[ServiceContract]
public class EchoService : IEchoService {
[WebGet(UriTemplate="EchoMe?val={theValue}, ResponseFormat=WebMessageFormat.Json)]
public string EchoMe(string theValue) {
return theValue;
}
}
If you handle your calls this way, you can separate out your service logic from your presentation (ASPX files), and this allows for easier testing and you can also separate responsibilities from those who build the UI from those that build the business functionality.
I have to admit I'm more of a jQuery person when it comes to this, but I thought it's a great exercise to figure out how the XmlHttpRequest works under the hood. It makes you appreciate what jQuery (or similar framework) provides.
Here's a nice overview of the XmlHttpRequest object and how to use it: http://www.jibbering.com/2002/4/httprequest.html
I hope this helps.
function GetXmlHttpObject(handler) {
var objXMLHttp = null
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest()
}
else if (window.ActiveXObject) {
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp;
}
function GetDropDown() {
function stateChanged(StatesUpdated) {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
document.getElementById('updateplace').innerHTML = xmlHttp.responseText;
//"updateplace" is you div id which will hold the new data or new page
if (navigator.appName != "Microsoft Internet Explorer") {
}
}
else {
//alert(xmlHttp.status);
}
}
xmlHttp = GetXmlHttpObject()
if (xmlHttp == null) {
alert("Browser does not support HTTP Request");
return;
}
url = "xyz.aspx" //this might be sent to any post data
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
with the above code you can send data to any .cs file also where you can change the data and load it in a new page which will load in the update div and the method should redirect to the new aspx file.
I hope you got the logic :)
if you have any doubts reach me # sankalpa.sam#gmail.com
I know it's not MVC that you're doing, but have a look at the MVC section of the ASP.NET site and you will find a lot of examples of AJAX calls there - MVC doesn't use those dreadful script-soup creating .NET objects. Most will probably be using jQuery - this is an open-source javascript library that can plug into any web app and provides some really nice functionality.
Maybe u r looking for this:
function ajaxscript(){
$.ajax({
type: "POST",
url: |url/methodName|,
data: |variable_name|,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: |some javascript here|,
error: |some javascript here|
});
How do I access Jquery Treeview inside the .aspx file upon form submit?
also, Can I add nodes to Jquery Treeview on the fly? (on the client side)
I am using asp.net web forms, c#
EDITED:
someone mentioned the following in one of the questions:
"on form submit, someone is going to have to write code on the client to collect that data and send it via Ajax to a server method"
how is this done?????
Well, I think I've found what you want. Take a look here.
In brief, you must define a WebMethod on your server side, and then you can easily access it using jQuery. An exellent working example is under the link above, and here I'll modify it to show how you can pass arguments. So...
In your page code-behind *.cs:
// We'll use this class to communicate
public class Dog
{
public string Name { get; set; }
public string Color { get; set; }
}
// This is your page, in my case Default.aspx
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public static string ProcessData(Dog myDog)
{
return "Your " + myDog.Color + " dog's name is " + myDog.Name + "!";
}
}
Then on your *.aspx:
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="json2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnProcess").click(function() {
// This is what we want to send to the server
var dogItem =
{
Color: $("#txtColor").val(),
Name: $("#txtName").val()
};
// And this is how it should be sent - in serialized way
var dogItemSerialized = JSON.stringify(dogItem);
$.ajax({
type: "POST",
url: "Default.aspx/ProcessData",
data: "{'myDog':" + dogItemSerialized + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").text(msg.d);
}
});
});
});
</script>
Color: <input id="txtColor" type="text" /><br />
Name: <input id="txtName" type="text" /><br />
<input id="btnProcess" type="button" value="Click Me" />
<div id="result"></div>
So here you fill textboxes and then your data is sent to the server which understands it as a Dog object. Pay attention to arguments passing, because this is the most confusing part. You should pass them in JSON format, which is a little bit "too-much-stringy". So I use here json2.js script which helps to convert usual javascript object into JSON-serialized string (JSON.stringify() method). It is available here. But it is still rather ugly =) It is important that I pass argument called "myDog" which value is the serialized dogItem. Because this is exactly what the server expects to get (so, for example, I can't change the argument name, this won't work:
data: "{'someAnotherArgumentName':" + dogItemSerialized + "}"
And the last thing. Pay attention to the following line:
success: function(msg) {
$("#result").text(msg.d);
}
If you are working with ASP.NET prior to 3.5 (for example, ASP.NET 2.0), then you'll need to write just $("#result").text(msg) instead of msg.d. Only ASP.NET 3.5 encapsulates all the data under "d" member for some reason...
Anyway, in the above article you can find useful links (both inside the article and in comments), so you can read more about arguments, "msg.d" and so on.
I hope this helps!
Since jQuery Treeview is a client-side component, you can't access it from the server-side. So in order to pass any data from your tree to the server, you have to write client-side javascript code (actually jQuery code). The same thing regarding adding nodes to the treeview on the fly: only using client-side jQuery code. Remember that your C# on the server-side has no idea about your TreeView.
The integration between jQuery and ASP.NET WebForms is rather problematic and "not so natural", because ASP.NET is built on different concept... So if you are working with ASP.NET WebForms, I would suggest you to use server-side components instead (it can be Microsoft's own ASP:TreeView or other 3rd-party WebForms-aimed components). Alternatively, you can try the new ASP.NET MVC Framework - it is built on more common (for other web-development platforms) concept, and the integration between it and jQuery is straightforward (actually jQuery is even shipped with it).
Don't get me wrong... I am not saying that the integration between jQuery and ASP.NET WebForms is totally impossible. It is possible. But you'll need to do "not-so-beautiful" things and work hard for every simple operation. If you still want to use jQuery, then use it only for the client-side animations...
UPDATE: As for this quote - "on form submit, someone is going to have to write code on the client to collect that data and send it via Ajax to a server method" - well, this is exactly what I am talking about. On the client-side you call javascript method when submitting the form (for example, by setting onclick='mymethod();' on your "Submit" button). This code does what it needs to do and then... it is supposed to perform AJAX call using jQuery nice syntax. But this won't work with ASP.NET WebForms, as I've explained before. Well, you can read about Microsoft AJAX Client-side library (here: http://msdn.microsoft.com/en-us/magazine/cc163300.aspx), perhaps this will help. But I still think that this integration won't be easy and straightforward. Use jQuery for the animation and ASP.NET server-side components for all other things!