1

我需要通过javascript获取自定义控件中的最新文本集。当我试图从服务器控件中获取选定的文本时,它总是返回默认文本而不是修改后的文本。如何在 servercontrol 中保留 javascript 设置的最新值?以下是供您参考的完整代码..

服务器控制1.cs

[assembly: WebResource("ServerControl1.Scripts.JScript1.js", "text/javascript")]
namespace ServerControl1
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ServerControl1 : WebControl
{
    public List<string> ListItems
    {
        get
        {
            return ViewState["items"] as List<string>;
        }
        set
        {
            ViewState["items"] = value;
        }
    }

    public string Text
    {
        get
        {
            return (FindControl("middleDiv").FindControl("anchorID") as HtmlAnchor).InnerText;
        }
        set
        {
            ((FindControl("middleDiv").FindControl("anchorID") as HtmlAnchor)).InnerText = value;
        }
    }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        HtmlGenericControl selectedTextContainer = new HtmlGenericControl("div");
        selectedTextContainer.ClientIDMode = System.Web.UI.ClientIDMode.Static;
        selectedTextContainer.ID = "middleDiv";

        HtmlAnchor selectedTextAnchor = new HtmlAnchor();
        selectedTextAnchor.ClientIDMode = System.Web.UI.ClientIDMode.Static;
        selectedTextAnchor.ID = "anchorID";
        selectedTextAnchor.HRef = "";
        selectedTextContainer.Controls.Add(selectedTextAnchor);

        HtmlGenericControl unList = new HtmlGenericControl("ul");

        foreach (string item in ListItems)
        {
            HtmlGenericControl li = new HtmlGenericControl("li");
            HtmlAnchor anchor = new HtmlAnchor();
            anchor.HRef = "";
            anchor.Attributes.Add("onclick", "updateData()");
            anchor.InnerText = item;
            li.Controls.Add(anchor);
            unList.Controls.Add(li);
        }

        selectedTextContainer.Controls.Add(unList);
        Controls.Add(selectedTextContainer);

        ChildControlsCreated = true; 
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        string resourceName = "ServerControl1.Scripts.JScript1.js";

        ClientScriptManager cs = this.Page.ClientScript;
        cs.RegisterClientScriptResource(typeof(ServerControl1), resourceName);
    }
 }
}

JScript1.js

function updateData() {
var evt = window.event || arguments.callee.caller.arguments[0];
var target = evt.target || evt.srcElement;
var anchor = document.getElementById("anchorID");
anchor.innerText = target.innerText;
return false;
}

测试页代码隐藏

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
     List<string> items = GetDataSource();
     ServerControl1.ListItems = items;
     ServerControl1.Text = "Select ..";
  }
}
protected void ClientButton_Click(object sender, EventArgs e)
{
   string selectedText = ServerControl1.Text;
 }
4

1 回答 1

2

The server won't get your client changes unless you POST the changes to him. Your HtmlAnchors are being rendered in HTML as <a> controls, and these type of controls won't POST anything to the server.

You're going to need an <input> control to input the changes into the server (that's why they're called input controls after all). I suggest an <input type=hidden> to hold the value of the anchor.innerText and keeps its state.

Your Javascript function needs to be modified so it updates the anchor.innerText AND updates the hidden input value as well. This way when the page gets posted back to the server you can retrieve the updated and client-modified value from the hidden field.

First you need to define as private fields your selectedTextAnchor and the hiddenField you are going to insert. This is because you need to access them in your CreateChildControls method as well as in the getter and setter of yout Text property. Much in the way the partial designer classes define the controls you want to have available in code-behind.

ServerControl.cs

private HtmlAnchor selectedTextAnchor;
private HtmlInputHidden hiddenField;

In the CreateChildControls method you need to insert the hidden field.

You'll notice I removed the use of ClientIDMode.Static. Using that mode would make your client controls to have the same fixed IDs and Javascript might get confused when you have multiple copies of your ServerControl in a page, and thus losing the reusable purpose of a custom control.

Instead, you need to provide your Javascript function with the ClientID's of the controls it needs to modify. The key here is that you need to attach your controls to the Control's hierarchy BEFORE you try to get their ClientID's.

As soon as you do this.Controls.Add(dummyControl), you're making dummyControl to become a part of the Page and its dummyControl.ClientID will be suddenly changed to reflect the hierarchy of the page you're attaching it into.

I changed the order at which your controls are attached to the Control's collection so we can grab their ClientID's at the time we build the onclick attribute and pass the parameters so your Javascript function knows which anchor and hiddenField to affect.

ServerControl.cs

protected override void CreateChildControls()
{
    base.CreateChildControls();

    // Instantiate the hidden input field to include
    hiddenField = new HtmlInputHidden();
    hiddenField.ID = "ANCHORSTATE";

    // Insert the hiddenfield into the Control's Collection hierarchy
    // to ensure that hiddenField.ClientID contains all parent's NamingContainers
    Controls.Add(hiddenField);

    HtmlGenericControl selectedTextContainer = new HtmlGenericControl("div");
    // REMOVED: selectedTextContainer.ClientIDMode = System.Web.UI.ClientIDMode.Static;
    selectedTextContainer.ID = "middleDiv";

    selectedTextAnchor = new HtmlAnchor();
    // REMOVED: selectedTextAnchor.ClientIDMode = System.Web.UI.ClientIDMode.Static;
    selectedTextAnchor.ID = "anchorID";
    selectedTextAnchor.HRef = "";
    selectedTextContainer.Controls.Add(selectedTextAnchor);

    // Insert the selectedTextContainer (and its already attached selectedTextAnchor child) 
    // into the Control's Collection hierarchy
    // to ensure that selectedTextAnchor.ClientID contains all parent's NamingContainers
    Controls.Add(selectedTextContainer);

    HtmlGenericControl unList = new HtmlGenericControl("ul");

    foreach (string item in ListItems)
    {
        HtmlGenericControl li = new HtmlGenericControl("li");
        HtmlAnchor anchor = new HtmlAnchor();
        anchor.HRef = "";

        // The updateData function is provided with parameters that will help
        // to know who's triggering and to find the anchor and the hidden field.
        // ClientID's are now all set and resolved at this point.
        anchor.Attributes.Add("onclick", "updateData(this, '" + selectedTextAnchor.ClientID + "', '" + hiddenField.ClientID + "')");
        anchor.InnerText = item;
        li.Controls.Add(anchor);
        unList.Controls.Add(li);
    }

    selectedTextContainer.Controls.Add(unList);
}

Note the use of the keyword this in the updateData function, it'll help us to grab the object that is triggering the action. Also note that both Id's are passed as strings (with single quotes)

The Javascript function would need to be modified so it updates the anchor and the hidden input field.

JScript1.js

    function updateData(sender, anchorId, hidFieldId) {
            // Update the anchor
            var anchor = document.getElementById(anchorId);
            anchor.innerText = sender.innerText;
            // Update the hidden Input Field
            var hidField = document.getElementById(hidFieldId);
            hidField.value = sender.innerText;
            return false;
        }

The last thing to do is change the way you are setting and getting your Text property.

When you GET the property you need to check if it's a Postback, and if it is, then you want to check if among all the info that comes from the browser there is your HiddenInputField. You can grab all the info coming from the client right at the Request object, more specifically, in the Request.Form.

Request.Form.AllKeys

All enabled input controls on your page will be part of the Request.Form collection, and you can get their values by using Request.Form[anyInputControl.UniqueID]. Note that the key used for this object is the UniqueID, NOT ClientID.

Once you get your client-modified value from the hidden input, you assign its value to the selectedTextAnchor, otherwise it'll go back to the original "Select..." text.

When you SET the property, you just need to assign it to the selectedTextAnchor.

In both GET and SET you need to call EnsureChildControls(), which will actually call your CreateChildControls() to make sure that your selectedTextAnchor and hiddenField controls are instantiated before you try to get some of their properties. Pretty much the same way that it's done in Composite Controls.

ServerControl.cs

public string Text
{
    get
    {
        EnsureChildControls();
        if (this.Page.IsPostBack)
        {
            string HiddenFieldPostedValue = Context.Request.Form[hiddenField.UniqueID];
            // Assign the value recovered from hidden field to the Anchor
            selectedTextAnchor.InnerText = HiddenFieldPostedValue;
            return HiddenFieldPostedValue;
        }
        else
        {
            return selectedTextAnchor.InnerText;
        }
    }
    set
    {
        EnsureChildControls();
        selectedTextAnchor.InnerText = value;
    }
}

This way you can have a control that recognizes the changes made in client. Remember that server won't know any change in client unless you notice him.

Another approach would be to notice the server everytime you click a link through an ajax request, but this would require a whole new different code.

Good luck!

于 2012-05-24T18:32:07.397 回答