Domanda

I would have believed that this question has an obvious answer, but I cannot seem to find any. I have an ASP.Net MasterPage which has a content page in which there are several dynamically created input controls. When I post the form which contains them, I want to retrieve their values. That is only possible using the name attribute of the control and calling Request.Form[name].

Since the input controls are part of a ContentPlaceHolder, their name attribute is assigned the UniqueId of the control, which is a string that could look like this for example: "ctl00$skts_body_div$MyNameId".

The above name in the example is not a randomly generated name, but it depends on the structure of the controls parents, hence it is not that easy in a postback to generate the name "ctl00$skts_body_div$MyNameId", so that I can call Request.Form["ctl00$skts_body_div$MyNameId"].

What is the best practice way of retrieving the posted data?

The platform is .Net 4.0

Thanks Jihad

È stato utile?

Soluzione

I found out that I could set the name attribute to be equal to the id using javascript in the browser. This can be done easily with jquery, but if you do not use jquery, then another option is to iterate through input elements, and other elements which are possible to post back.

I think the only drawback is that you have to make sure that you only change the dynamically created controls, and not hit any runat="server" ASP controls, since those use the name attribute to assign their values to.

The following code is the javascript I use:

function SetControlNamesToId() {
    var inputObjects = document.getElementsByTagName('input');
    for (i = 0; i < inputObjects.length; i++) {
        if (inputObjects[i].type == 'checkbox' ||
            inputObjects[i].type == 'radio' ||
            inputObjects[i].type == 'text' || 
            inputObjects[i].type == 'hidden') {
            SetNameToId(inputObjects[i]);
        }
    }

    var selectObjects = document.getElementsByTagName('select');
    for (i = 0; i < selectObjects.length; i++) {
        SetNameToId(selectObjects[i]);
    }

    var textAreaObjects = document.getElementsByTagName('textarea');
    for (i = 0; i < textAreaObjects.length; i++) {
        SetNameToId(textAreaObjects[i]);
    }
}

function SetNameToId(control)
{
    if (control.id && control.id != "") {
        control.setAttribute("name", control.id);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top