简体   繁体   English

在jquery中获取和设置ASP.NET属性

[英]Getting and setting ASP.NET attributes in jquery

I am adding a new attribute to a DataList control in asp.net. 我将新属性添加到asp.net中的DataList控件。 I want to set the attribute on the server in C#. 我想在C#的服务器上设置属性。 I then want to modify it in jQuery on the client, and get the new value of the attribute in C# back on the server. 然后,我想在客户端的jQuery中对其进行修改,并在服务器上的C#中获取该属性的新值。 I think if I initialize the attribute to say "0" in my .aspx code, it get reset to "0" during the postback. 我认为,如果我在.aspx代码中将属性初始化为说“ 0”,则在回发期间它将重置为“ 0”。

So, I'm using DataList.Attributes.Add() to create and init the attribute value during my render. 因此,我正在使用DataList.Attributes.Add()在渲染期间创建和初始化属性值。 On the client, I use .attr in jQuery to modify the value. 在客户端上,我在jQuery中使用.attr来修改值。 During the postback on the server, I use DataList.Attributes["attributeName"] to get the new value, but it's null. 在服务器上进行回发期间,我使用DataList.Attributes [“ attributeName”]获取新值,但是它为null。 I've changed EnableViewState for the DataList, its parent, and grandparent to true and false, but I still get a null value. 我已将DataList及其父项和祖父母的EnableViewState更改为true和false,但仍然得到一个null值。

Is there a way to create and init an attribute on the server, modify it in jQuery on the client, and get the new value in C# back on the server? 有没有一种方法可以在服务器上创建和初始化属性,在客户端的jQuery中对其进行修改,并在服务器上的C#中获取新值?

You could make an AJAX call in wich you send the changes made it with jquery to some webservices method in your code behind to handle it. 您可以进行AJAX调用,将使用jquery进行的更改发送到后面代码中的某些webservices方法以进行处理。

AJAX jquery post change call: AJAX jQuery帖子更改调用:

$.ajax({
    type: 'POST',
    url: 'Default.aspx/Checksomething',
    data: '{"userValuePostChanged ": "' + DtLValue+ '"}',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(msg) {
        alert("Result: " + msg);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Error: " + textStatus);
    }
});

webservices C# 网络服务C#

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Checksomething(string userValuePostChanged)
{
    //Do some stuff with userValuePostChanged

    return "something else"
}

This are the links where I took the examples: 这是我进行示例的链接:

consume .net web service using jquery 使用jQuery消耗.net Web服务

How to use jQuery to make a call to c# webservice to get return value 如何使用jQuery调用C#Web服务以获得返回值

http://www.codeproject.com/Articles/66432/Consuming-Webservice-using-JQuery-ASP-NET-Applicat http://www.codeproject.com/Articles/66432/Consuming-Webservice-using-JQuery-ASP-NET-Applicat

A server control's attributes are persisted in the page viewstate. 服务器控件的属性保留在页面viewstate中。 On postback the server control is re-created, and, its attribute values are re-created by parsing the viewstate value, from the posted data. 在回发时,将重新创建服务器控件,并通过从已发布的数据中解析viewstate值来重新创建其属性值。

Hence any attempt to modify a server-created-control-attribute, or, add an attribute on a server-control from the client will not work. 因此,任何尝试从客户端修改服务器创建的控件属性或在服务器控件上添加属性的尝试都将无效。 (More precisely it won't be very straight forward even if it might be possible). (更确切地说,即使有可能,它也不会很简单)。

Anyhow, a browser is "programmed" to send (over the wire) data held inside any html input or select control (hope I didn't miss anything) nested inside the html form. 无论如何,对浏览器进行“编程”以发送(通过电线)保存在任何html输入中的数据或嵌套在html表单中的select控件(希望我什么都没错过)。 Further, all such controls need to be identified by the value specified by the name attribute. 此外,所有这些控件都需要通过name属性指定的值来标识。 For eg 例如

<form method="post" action="default.aspx">
<input type="text" name="foo" value="123"/>
<input type="submit" value="submit to server"/>
</form>

If one such form is submitted to a server like ASP.NET (which is an abstraction of IIS which implements the CGI standard), you can get the value of the textbox by doing something like: 如果将一种这样的形式提交给类似ASP.NET的服务器(这是实现CGI标准的IIS的抽象),则可以通过执行以下操作来获取文本框的值:

string fooValue = Request.Form["foo"];

A browser program is usually programmed to send data corresponding the name and value attributes only. 通常将浏览器程序编程为仅发送与namevalue属性相对应的数据。

Now, since you are looking at getting more than one kind of data on the server, but still associated with a single control, your options are to go with any of the following: 现在,由于您希望在服务器上获取多种数据,但仍与单个控件相关联,因此您可以选择以下任一项:

  1. Access the value from two separate controls on the server. 从服务器上的两个单独的控件访问该值。 However, its your job to figure their are associations. 但是,您的工作要弄清楚它们是关联。
  2. You can think of a user control approach, which ultimately is like the above but if written will give you a neat encapsulation. 您可以想到一种用户控制方法,该方法最终与上面的方法类似,但是如果编写了该方法,则会为您提供简洁的封装。

Here is a small example of the 2nd approach: 这是第二种方法的一个小例子:

CompositeControl.ascx: CompositeControl.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CompositeControl.ascx.cs" Inherits="WebApp.Attributes.CompositeControl" %>

<label>Enter Name</label>
<asp:TextBox runat="server" ID="tbxName"></asp:TextBox>
<asp:HiddenField ID="hdnAge" runat="server" />

CompositeControl.ascx.cs: CompositeControl.ascx.cs:

using System;

namespace WebApp.Attributes
{
    public partial class CompositeControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!string.IsNullOrEmpty(this.HiddenFieldClientId))
            {
                hdnAge.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                hdnAge.ID = this.HiddenFieldClientId;
            }
        }

        public string Name
        {
            get
            {
                return tbxName.Text;
            }
            set
            {
                tbxName.Text = value;
            }
        }

        public int Age
        {
            get
            {
                return int.Parse(hdnAge.Value);
            }
            set
            {
                hdnAge.Value = value.ToString();
            }
        }

        public string HiddenFieldClientId { get; set; }
    }
}

default.aspx: default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApp.Attributes._default" %>

<%@ Register src="CompositeControl.ascx" tagname="CompositeControl" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.1.0.min.js"></script>
    <script>
        $(function () {
            $('#tbxAge').val($('#personAge').val());
            $('#btnSetAge').click(function () {
                $('#personAge').val($('#tbxAge').val());
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <uc1:CompositeControl ID="CompositeControl1" runat="server" HiddenFieldClientId="personAge" />
        <br />
        <input id="tbxAge" type="text" />
        <input id="btnSetAge" type="button" value="Set" />
        <p>Hit <strong>set</strong> before clicking on submit to reflect age</p>
        <asp:Button runat="server"  ID="btnSubmit" Text="Submit" 
            onclick="btnSubmit_Click" /> 
        <br />
        <asp:Literal runat="server" ID="ltrlResult"></asp:Literal>
    </div>
    </form>
</body>
</html>

default.aspx.cs: default.aspx.cs:

using System;

namespace WebApp.Attributes
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CompositeControl1.Age = 23;
                CompositeControl1.Name = "Default";
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ltrlResult.Text = string.Format("<p>{0}</p><p>{1}</p>", CompositeControl1.Name, CompositeControl1.Age);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM