0

Is it possible to get dynamically added elements in C# after the DOM has loaded. Here is my example below.

The idea is to have rows added, dynamically from user intervention, then the user submits the form and the C# codebehind will iterate through each, new added row.

However, no matter how many rows are added, the C# will only count 1 row.

Here is the HTML / Jquery / C#

HTML

Before new rows are added to table.

<table id="tblRecordedBags" runat="server" class="tblBags">
    <tr>
        <th>Amount</th><th>Drop Bag Number</th><th>Edit</th><th>Remove</th>
    </tr>
</table>
<input type='text' class='txtBagNum' id='txtBagNum'>

jQuery

Used to add new rows.

$('.addBag').on('click', function(){
  $(".tblBags").append(
            '<tr class="bag"><td class="bag">'
                + $(".total").val() + '</td><td class="bagID">'
                + $(".txtBagNum").val() + '</td>'
                + "</tr>'
});

C# Codebehind

Quick debug write

System.Diagnostics.Debug.Write(tblRecordedBags.Rows.Count);
1
  • Out of interest is this MVC or Forms? Commented Dec 5, 2012 at 6:30

2 Answers 2

1

That is happening because you are accessing it from the server side where in the server side has no knowledge of any changes to the DOM.

The new rows are added in the browser but the default page remains the same which resides in .aspx files and those are not modified in the first place.

To get the right output you can actually add rows in C# and then try.

Sign up to request clarification or add additional context in comments.

2 Comments

Use Ajax to have asp add the rows? Like a post back?
Yes.. that should be of help..Otherwise you may have to use Update Panels
1

I think that ASP.NET is not prepared for javascript.

An easy way is to add each row through server side with an update panel.

Another way is to try to load all data from the rows in a Hidden Field before submit (encoded with JSON for example)

1 Comment

Added: each element in the ASP.NET page is declared in the ViewState, so you cant easily add elements that haven´t been declared by .NET code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.