asp.net: (c# client-side) how to access html element created after page loads?

て烟熏妆下的殇ゞ 提交于 2019-12-10 16:33:20

问题


Imagine this,

Step 1: ASPX Page Loads.
Step 2: Button fires a script that creates a html element (div, span, etc) with an id or class tag, including runat server attribute.

and my problem is,

Final Step: From my C# file, how to access that element and get it's inner html, so I can save it to a string?

PS: i'll use that string to save it in my mssql database.


回答1:


You cannot create a "real" runat=server element/control without doing a full postback to the server.

The best approach may be to write some script that stores the innerHTML into an ASP.Net hidden field right before you submit the page. You can then access the value of this hidden field to grab the data.

If you're wanting to dynamically create multiple objects, you'll need to use standard html hidden input fields instead, since you can't create asp.net server controls via javascript.

<input type="hidden" name="fieldData_1" value="control 1 html content">
<input type="hidden" name="fieldData_2" value="control 2 html content">

You'll then be able to access these hidden fields from the Request.Form object:

Request.Form["fieldData_1"]

Knowing this, you can now iterate over the form data and process all of your dynamic fields

foreach (string fieldData in Request.Form)
{
    if(fieldData.Contains("fieldData_"){
        //process the data for each field
    }
}

It is also possible to avoid using hidden fields all together and just pass your data to the server directly using the __doPostback('', '') method. This could be implemented in many different ways, so I'll just refer you to http://dopostback.net to read up on how the method works.




回答2:


Add runat="server" attribute to the tag to make it HTML Control and can be accessible from .cs file by its ID




回答3:


I think you need to post the element inner HTML back to the server. What I would do, in a client function, get the inner HTML of the newly created element, store it in a hidden field, then call __doPostBack('<hidden element id>', '');



来源:https://stackoverflow.com/questions/10578886/asp-net-c-client-side-how-to-access-html-element-created-after-page-loads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!