【问题标题】:how can I find the html element with C#如何使用 C# 找到 html 元素
【发布时间】:2020-03-12 18:30:18
【问题描述】:

我的.aspx 代码中有这一行:

 <div id="view" class="g2" runat="server">
 </div>

但是当我想在 C#(aspx.cs) 中找到这个元素并为其发送数据时,C# 无法通过这种方式找到它:

view.Controls.Add(item);

*item 是我通过这段代码制作的 html 元素:

for(int i=0; i<foods.Count; i++)
{
    HtmlGenericControl item = new HtmlGenericControl("div");
    item.Attributes["class"] = "items";
    item.Style["border_bottom"] = "3px solid aqua";

    HtmlImage img = new HtmlImage();
    img.Src = foods[i].picGet();

    HtmlGenericControl mask = new HtmlGenericControl("div");
    item.Attributes["class"] = "mask";

    HtmlGenericControl h2 = new HtmlGenericControl("h2");
    item.InnerHtml = foods[i].fnameGet();

    HtmlGenericControl price = new HtmlGenericControl("span");
    item.Attributes["class"] = "price";
    item.InnerHtml = foods[i].priceGet().ToString() + "ریال";

    HtmlGenericControl desc = new HtmlGenericControl("p");
    item.InnerHtml = foods[i].describeGet();

    mask.Controls.Add(h2);
    mask.Controls.Add(price);
    mask.Controls.Add(desc);

    item.Controls.Add(img);
    item.Controls.Add(mask);

    view.Control.Add(item);
}
  • 我已经写了命名空间System.Web.UI.HtmlControls
  • 我看到一门课程做同样的事情并且很成功
  • 错误是即使我的 Visual Studio 也找不到我在 for 循环的最后一行中使用的 view

【问题讨论】:

  • 这能回答你的问题吗? c# - reading HTML?
  • 你得到的错误究竟是什么?请注意,您确实写了 view.Control 而不是 view.Controls(复数)
  • 代码审查:你设置了很多item.InnerHtml。我认为您的意思是您刚刚创建的控件而不是“项目”

标签: c# html asp.net htmlcontrols


【解决方案1】:

您可以使用Control.FindControl 来搜索带有指定id 参数的控件,如下所示:

Control view = FindControl("view");
//Then add your item to div
view.Controls.Add(item);

【讨论】:

    猜你喜欢
    • 2016-08-29
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2012-04-18
    • 2022-01-26
    相关资源
    最近更新 更多