Question

I have a .aspx file with:

<%@ Page Language="C#" AutoEventWireup="true" Inherits="baa.foo" CodeFile="foo.aspx.cs" %>
<input runat="server" id="name" name="name" />

and foo.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace baa
{
    public partial class foo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string s = name.Text;
        }
    }

How do I to name HTML control be know by foo class in .cs file? it returns an error:

Error 61 The name 'name' does not exist in the current context

NOTE: The HTML was not written by me. I'm editing .html pages to .aspx ones to make them dymically and I be able to get values from them by using C# code

Était-ce utile?

La solution

By default, HTML elements within an ASP.NET file are treated as literal text and you cannot reference them in server-side code. To make these elements programmatically accessible, you can indicate that an HTML element should be treated as a server control by adding the runat="server" attribute.

and Also

HTML server controls must reside within a containing form tag with the runat="server" attribute.

Reference: HTML Server Controls

Now you can access your control from code behind but here you can't get Text property of input html control, you need to get Value property.

If you convert html page to ASPX then you can replace relevant ASP.NET control with existing HTML controls. for example you can use input type text with ASP.NET TextBox control

Autres conseils

use name.value instead of name.text

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top