Changing the generated ASP.Net <form> id?

落爺英雄遲暮 提交于 2019-11-27 15:07:37

问题


In my ASP.Net page I have

<form id="MasterPageForm" runat="server">

However, whenever the markup is generated, it turns into

<form name="aspnetForm" method="post" action="SomePage.aspx..." id="aspnetForm">

Is it possible to set what the generated HTML id for the form is?


回答1:


Note: you are seeing "aspnetForm" because you are using a master page.

I found your solution in this thread...

http://forums.asp.net/p/883974/929349.aspx

In short, this is what the answer is from that link:

Here's the responsible code for that error:

public override string UniqueID
{
      get
      {
            if (this.NamingContainer == this.Page)
            {
                  return base.UniqueID;
            }
            return "aspnetForm";
      }
}

As you can see, when the naming container is different from the current page (something that happens when you use a master page) the UniqueID property return "aspnetForm". this property is rendered into the name attribute that is sent to the client in the form tag. so, if you really need to, you can create your own form by inheriting from htmlform and then override the UniqueID property or the Name property (this may be a better option).

An example custom HtmlForm class could be like this:

public class Form : System.Web.UI.HtmlControls.HtmlForm
{
    public Form() : base() { }

    public override string UniqueID
    {
        get {
            if (this.NamingContainer == this.Page)
            { return base.UniqueID; }

            return "f";
        }
    }
}

Note: You can certainly change the name of the form from "f" to something else, or have it read a dynamic value, say from a web.config file or so.

and used like so

<%@Register tagprefix="LA" Namespace="Mynamespace"%>
...
<LA:form runat="server" id="frm">
...
</LA:form>



回答2:


Set the "clientidmode" attribute to "static" on the form tag to prevent the framework from overriding it with "aspnetForm". This was driving me nuts for hours.




回答3:


I am agree with @Sumo's comment under accepted answer and I had the same situation.

In ASP.NET 4.0, master page, if a is not given an id, the rendered html will be automatically assigned one, such as .

Otherwise, the rendered html will have its original defined id.




回答4:


change in web config

<pages controlRenderingCompatibilityVersion="4.5" clientIDMode="AutoID"/>

to

<pages controlRenderingCompatibilityVersion="4.5"/>


来源:https://stackoverflow.com/questions/3257369/changing-the-generated-asp-net-form-id

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