8

有谁知道是否可以在 .Net 服务器端利用 JQuery 的强大功能?

例如,我在后面的一些代码中有一些 HTML 作为字符串。有没有办法在它上面执行 JQuery?

我目前正在这样做...

假设这是字符串...

<input id='AddressSettings_txtFirstName' name='txtFirstName' 
value='#firstNameValue#' size='25' type='text'  class='val_required'/> 

我的 C# 这样做

 strHTML = strHTML.Replace("#firstNameValue#", customerInfo.FirstName);

这就是我将数据绑定到 HTML 的方式。

现在我想做的是不必添加#firstNameValue# 作为占位符并替换它,我想以某种方式在我的C# 代码中的HTML 字符串上执行一行JQuery。

strHTML = strHTML.ExecuteJQuery("$('#AddressSettings_txtFirstName').text('" 
         + customerInfo.FirstName + "')");

我在这里有什么选择?

4

6 回答 6

4

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.

于 2010-03-02T18:46:07.753 回答
1

您可能想要的是 HTML 敏捷包。你不能执行 JavaScript,但你可以做一些 DOM 操作。试一试http://htmlagilitypack.codeplex.com/

于 2014-03-12T11:16:57.677 回答
1

将 jQuery 与 jsdom 一起用于 Node.js。在服务器端使用 javascript 操作 DOM 元素的最简单方法。

于 2014-07-16T09:30:32.660 回答
0

这就是Java的答案。Here and Here 由某个名叫 John Resig 的人提供。(不确定他是否知道他在谈论 JQuery 时在说什么……眨眼眨眼)

现在 .Net 呢?

于 2010-03-02T19:21:29.840 回答
0

DOM 是浏览器特定的实体。因此,不能像您寻求的那样直接可用。但是,您可以确定您想要操作的内容,并在添加元素时使用.live()或调用您的 jQuery 代码来添加行为内容。至于变化:

<input id='AddressSettings_txtFirstName' name='txtFirstName'  
value='#firstNameValue#' size='25' type='text'  class='val_required'/>  

$('#AddressSettings_txtFirstName').change(function(){
// do stuff here
});

例如,当它发生变化时会触发。编辑:另一种选择是让客户端使用 ajax 和 JSON 提取数据 - 但这是您目前工作方法的一个小转变。

于 2010-03-02T18:56:09.873 回答
-1

这项技术ItsNat与您的愿望非常相似,坏消息......是基于 Java 的。

于 2011-01-18T15:41:50.527 回答