Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net 4.0: is there any equivalent of ClientIDMode for the names of INPUTs?

I have an asp:ListView whose ClientIDMode is set to Predictable. Its ItemTemplate contains an asp:textbox.

The ID of the textbox is acting as I expect it to, but its name is still using what looks like an AutoID-style algorithm:

<input name="lvFields$ctrl0$tbVal" id="lvFields_tbVal_somekey" type="text"/>

Is there a way for me to cause the name of the input to act like the ID does?

(Edit in response to questions below:)

The Name of the input element is what's in the POST data, so if a postback alters the list to which the ListView is bound (for example, exchanging two elements) the values from the textboxes end up associated with the wrong keys, because the framework is correlating them based on the Name and not the ID.

like image 798
Dan Davies Brackett Avatar asked Feb 11 '11 20:02

Dan Davies Brackett


2 Answers

You can change the name of an Input by using the method from the following post but modifying it slightly:

how to remove 'name' attribute from server controls?

I over-rode the RenderChildren method on a Page control as I just wanted full control of the HTML for a few controls:

protected override void RenderChildren(HtmlTextWriter writer)
{
    var unScrewNamesRender = new RenderBasicNameHtmlTextWriter(writer);
    base.RenderChildren(unScrewNamesRender);
}

private class RenderBasicNameHtmlTextWriter : HtmlTextWriter
{
    public RenderBasicNameHtmlTextWriter(TextWriter writer) : base(writer) { }

    public override void AddAttribute(HtmlTextWriterAttribute key, string value)
    {
        if (key == HtmlTextWriterAttribute.Name && value.Contains("POLine"))
        {
            value = value.Substring(value.LastIndexOf("$") + 1);
        }

        base.AddAttribute(key, value);
    }
}

You do need to know what you're doing if you attempt this, WebForms will think the control is missing so you can't use it in any postbacks. For my purposes, where I wanted to add an arbitrary number of multiple lines either server or client-side without having to deal with .Net Ajax controls, it works fine.

like image 64
mattmanser Avatar answered Oct 16 '22 06:10

mattmanser


I'm pretty sure you can't change the name, especially when you modify the ClientIDMode. As an alternative, you can add a Title attribute. VS will flag this as unknown in the server side code, but it renders correctly in the HTML. If you're doing some client-side manipulation, you can address the input as such:

<script type="text/javascript">
$(document).ready(function () {
$('input:text[title="TextBoxName"]').datepicker();
});
</script>
like image 27
Rich Dudley Avatar answered Oct 16 '22 05:10

Rich Dudley