Reputation: 9295
Let's say I have a master page where my <html>
element is defined. I then have a default.aspx page that uses said master page. How can I modify the <html>
tag from the code behind of default.aspx? In particular, I'd like to change the value of an attribute on it, "data-custom", so it renders as <html data-custom="my dynamic value">
.
Upvotes: 2
Views: 6600
Reputation: 7483
you can only access elements that are located inside the main form that runs on the server through the Request
object. you cant directly access the html.
you can however, give your element an id, and create a javascript function that will stick the dynamic data to the html, and will accept this data as argument as well, and then from the code behind you invoke this function on the page.
im not sure if u can access <html>
tag with javascript, but its worth a shot.
i will write an example for you, you can look into it meanwhile.
EDIT:
here is an example:
Aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function attachDataToHTML(myAttribute,myData) {
htmlElement = document.getElementsByTagName("html")[0];
var att = document.createAttribute(myAttribute);
att.value = myData;
htmlElement.setAttributeNode(att);
}
</script>
</head>
<body>
<form runat="server">
<asp:Button runat="server" Text="test" OnClick="Unnamed1_Click"></asp:button>
</form>
</body>
</html>
cs:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
string myCustomAttribute_Name="testAttribute";
string myCustomAttribute_Data="testData";
Page.ClientScript.RegisterStartupScript(
GetType(),
"someUniqueKeyWhatever",
"attachDataToHTML('"+myCustomAttribute_Name+"','"+myCustomAttribute_Data+"');",
true);
}
}
in the code behind you call the javascript function and pass her your custom attribute and data, and it adds it to the html element.
Upvotes: 2
Reputation: 166
you can simply give <html id="mainhtml" runat="server" >
mainhtml will be available in code behind, mainhtml.Attributes["data-custom"] = "my dynamic value";
. not the best Practice.
Upvotes: 5