jQuery server side DOM manipulation - asp.net

Does anyone know if it is possible to leverage the power of JQuery on the .Net serverside?
For example I have some HTML as a String in some code behind. Is there a way to execute JQuery on it?
I'm currently doing this...
Assume this is the String...
<input id='AddressSettings_txtFirstName' name='txtFirstName'
value='#firstNameValue#' size='25' type='text' class='val_required'/>
My C# does this
strHTML = strHTML.Replace("#firstNameValue#", customerInfo.FirstName);
And this is how I bind my data to my HTML.
Now what I would like to do is instead of having to add the #firstNameValue# as a place holder and replacing it I would like to somehow execute a line of JQuery on the HTML string in my C# code.
strHTML = strHTML.ExecuteJQuery("$('#AddressSettings_txtFirstName').text('"
+ customerInfo.FirstName + "')");
What are my options here?

For all intents and purposes, the answer is "no" (while there might be some obscure way of handling this, it's not the most optimal way).
It appears you are looking for a way to manipulate the HTML that is being produced on the server-side, which is a very legitimate desire, it's just that the approach on the server side using .NET (or other) technologies is radically different than how you would approach it on the client-side.
Because the content is already rendered on the client, the way you would apprach modifying it is different. On the server, the page is built of from various parts which ultimately render the HTML to the client, using data that the client doesn't necessarily have access to (as well as resources and libraries).
It's for that reason you want to use what's available on the server to accomplish what you are doing.
Whether you are using the WebForms model or MVC model of ASP.NET, there are mechanisms that allow you to bind to data without having to write out the tag yourself.
For example, in the WebForm model, you have the TextBox class which you can set the Text property on.
In ASP.NET MVC, there is the TextBox extension method on the InputExtensions class which allows you to pass the content of the textbox and the method will render the tag for you.

May be what you want is the HTML agility pack. You can't execute JavaScript, but you can do some DOM manipulation. Give it a try http://htmlagilitypack.codeplex.com/.

Use jQuery with jsdom for Node.js. Easiest way to manipulate DOM elements using javascript on the server-side.

The DOM is a browser specific entity. Thus, not directly available as you seek. However, you can determine just what you want to manipulate, and use either .live() or calling your jQuery code to add behavioral stuff as elements get added. As for change:
<input id='AddressSettings_txtFirstName' name='txtFirstName'
value='#firstNameValue#' size='25' type='text' class='val_required'/>
$('#AddressSettings_txtFirstName').change(function(){
// do stuff here
});
will fire when it changes for instance.
EDIT: One other option is to have the client pull the data using ajax and JSON - but that is a small shift in your method of working at present.

Well this is the answer for Java.Here and Here
Provided by some guy named John Resig. (Not sure he knows what hes talking about when it comes to JQuery...wink wink)
Now what about .Net?

This technology, ItsNat, is very similar to your desires, the bad news... is Java based.

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.

Critique this strategy

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.

On Creating Controls Dynamically or Not

I'm currently working on an ASP.NET 3.5 project, and I wanted to know your opinion regarding the following situation, which I happen to run into sometimes:
Let's say I've defined the following control of an imaginary component framework somewhere in my code:
<Window runat="server" ID="windowTest" />
Let's assume that with the above mentioned imaginary component framework it's possible to get a reference to my Window control from the client-side using its ID (for example to change its appearance):
function MyFunc(){
var win = GetWindow("windowTest");
}
Let's also assume that both code snippets are placed in different files, e.g. the JavaScript code in MasterPage.Master and the control in AnotherPage.aspx.
As you might already have noticed, the passing of the control's ID as a hard-coded string to the GetWindow function is a bit problematic here, since changing the control's ID is going to break the JavaScript function.
This situation surely smells like it needs a good ol' Replace Magic Number with Symbolic Constant refactoring. I can achieve this by dynamically creating the Window control and using a constant for the value of the control's ID:
AnotherPage.aspx:
Window windowTest = new Window();
windowTest.ID = Consts.ID_WINDOW_TEST;
form1.Controls.Add(windowTest);
MasterPage.Master:
function MyFunc(){
var win = GetWindow("<%= My.Namespace.Consts.ID_WINDOW_TEST %>")
}
My question now is: How do you handle such situations? Do you create all your controls dynamically (like shown in the example above) when running into this situation, and are there any drawbacks using this approach, e.g. Designer doesn't display the control anymore? Or do you say "Screw it, nobody's going to change that control's ID" and leave it hard-coded in your code? Or do you have other approaches to this situation?
I personally am a fan of the of the first option (refactoring), since a) it makes sure that a change to the ID is not going to break my code and b) I almost never work with the Designer, but I thought I'd ask this question on SO to get some valuable opinions on this.
Thanks in advance for all the responses.
Greetings,
Giu
Update / Clarification:
I made a small error in the first version of this question by stating that the code snippets are placed in the same file. Since both the control and the JavaScript method are located in the same file, there is no need to create the control dynamically and defining the control's ID using a constant; by defining the control directly in the .aspx file I could use its ID in the JavaScript method as follows: GetWindow("<%= windowTest.ID %>");
But, my problem is another one; the control and the JavaScript method are each placed in different files, in which case the mentioned approach of using the control's ID doesn't work anymore. Therefore I introduced the solution mentioned in my question with the constant and the dynamic creation of the control. I now corrected both the filenames in my question so that the correct scenario is described to which my question is related.
In 4.0 you can control the client ID that's generated in master/content page situations quite well. but i believe if someone changes the ID manually in the page at one place and not in the javascript code it will still be a problem. If you are the only one who'll be working on this code then you can always be mindful and refactor properly. Otherwise you can go in for the constants option or store the IDs in a separate resource file.
In my opionion there a two suitable solutions:
1) Use the JQuery framework to get ahold of the html element you want to adress via JavaScript. JQuery is designed to be able to work with autogenerated hierarchically created control IDs
2) Use .net Framework 4.0 and don't use autogeneration of the Control ID. (I've heard that this is a new feature in 4.0. I think in your situation it might be worth trying out)
Check out Rick Strahl's blog post entitled "A generic way to find ASP.NET ClientIDs with jQuery"... it seems to have some good ideas that could be of some help to you.
He uses jQuery, as the first responder suggested, but does it in a way that you are using ASP.NET's built-in ClientID property to get the actual id ASP.NET generates and uses a client-side friendly mechanism that enables you to write script code referencing controls that won't break with ID changes.

Which ASP.NET Page event is the best place for this type of code?

I have a relatively simple page that will do most of its operations on the client side using Javascript or JQuery. However, initially I do need to retrieve some data from the DB server based on QueryString parameters.
I plan on passing this data in the form of a JSON string to the script by an old-fashioned ASP manner ( var severData = <%=MyPublicData %>) block where MyPublicData is defined in CodeBehind as:
Public string MyPublicData;
The question is, which event in the ASP.NET page lifecycle is the best for this? Page_Init ? Page_Load? Also, is it worth the effort to do this in ASP.NET MVC. I did look at this possiblity but it seemed a little too much for a simple page like this where I do more 90% of the work on the client. Any thoughts on this?
Page_Load is more appropriate, but either will work.
It's very difficult to say if MVC is more appropriate for you application than webforms without knowing more about the application. However, if you don't want to abstract away the traditional web model then I'd go with MVC.
This kind of simple property or field assignment can go anywhere in the lifecycle. For lack of any other reason, you might as well stick it in Page_Load, since that method is usually waiting for you in the code-behind anyway.
well, on the contrary, if it uses mostly javascript with jQuery, I would recommend you to use MVC. you will not have any problem with the ids for instance.
There are workaround to use jQuery with webforms, but it is never perfectly clean regarding selecting the DOM.
MVC : a single action method where you will retrieve your data (preferably from a small repository) and 1 view where you display your data with total control over your html elements.
and jQuery will just fit perfectly for your clientside work.
You can get either to work; you can write public variables/fields to the client in ASP.NET web forms, although MVC has an edge due to the way it renders the UI.
So for MyPublicData, you could assign it a value at any part of the lifecycle; you can assign it in code-behind to a label or something like that, or if it's JS markup you can write it out using Page.ClientScript.RegisterStartupScript or RegisterClientScriptBlock... so you have multiple options.
In MVC, you would assign the value in the controller and render it in the UI, or with JQuery you can do controller requests real easy with $.ajax.

Resources