1

In my app I have a lot of the same HTML blocks so I don't want to repeat them.

I found out that I can select a block of HTML code and select Extract to User Control option.

It creates an .ascx file with content like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="div_field.ascx.cs" Inherits="Obipoly.layout.div_field" %>

<div class="field">
    <div class="status_bar">
        <div class="hotel_placeholder">
            <div class="house_placeholder"></div>
            <div class="house_placeholder"></div>
            <div class="house_placeholder"></div>
            <div class="house_placeholder"></div>
        </div>
        <div class="players_container">
            <div class="player_placeholder"></div>
            <div class="player_placeholder"></div>
            <div class="player_placeholder"></div>
            <div class="player_placeholder"></div>
       </div>
    </div>
    <div class="field_name"></div>
    <div class="field_image"></div>
    <div class="field_price"></div>
    <div class="field_owner"></div>
</div>

I can now use this block in my .aspx file:

<uc1:div_field runat="server" ID="field39" />

Now I need to iterate through my elements (id=field0, id=field1,...) and change some data.

How can I get a reference to each element and find each child in it?

I tried:

for (var i = 0; i < 40; ++i) {
    var fieldId = "#field" + i.toString();
    var field = $(fieldId);
    alert(field); //displays object Object
    field.find(".field_name").append($("<p/>", {
        text: i
    }))
}

But nothing happens. I'm not sure if I can do

var field = $(fieldId);

as if my element were an ordinary html tag.

What if want to find an element which shares the same class with others, e.g. I want to get third <div> with player_placeholder class and give it a unique id?

Or the only way is to create all the elements with JavaScript at runtime?

Thanks.

PS. The reason I can't get any of my fields is that in my DOM I have only body of my control. I thought I would have:

<div id="field20">
    <div class="field">
        ...
    </div>
</div>

But actually it is:

<div class="field">
   ...
</div>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Cahir09
  • 501
  • 6
  • 14
  • Create a property on the `uc` then pass in the ID then render that property within the control. More info here: http://stackoverflow.com/questions/2201312/pass-data-from-a-asp-net-page-to-ascx-user-controls-loaded-dynamically – freedomn-m Dec 03 '15 at 08:49

1 Answers1

0

The problem here is that if you were to inspect the ID that asp.net created for you it will not be field39 it would be some custom one, you can however override this behaviour by using ClientIDMode

<uc1:div_field runat="server" ID="field39" ClientIDMode="static" />
Łukasz Trzewik
  • 1,165
  • 2
  • 11
  • 26