如何在asp.net中动态地在页面上加载某个html代码?
例如:我需要验证密码。如果密码错误..在页面加载时,应该有一个名为“error”的div出现在名为bodyWrapper的div旁边的顶部
我目前的做法是将其内联在aspx文件中编写..但我知道这不是混合内联和代码的正确方法。
<div id="content">
<%
Session["loginError"] = "loginError";
try
{
if (Session["loginError"].ToString() == "lockout")
{
%>
<div class="errorMessage">
Your Account has been locked out. Please wait
<% Response.Write(Session.Timeout); %>
minutes and try again.
<br />
</div>
<%
}
else if (Session["loginError"].ToString() == "loginError")
{
%>
<div class="errorMessage">The user ID or password you entered does not match our records. Please try again. <br />
You may also securely recover your <a href="#">User ID</a> or reset your <a href="#">Password</a> online.
</div>
<%
}
}
catch
{
//cssClassName = "loginTextInput";
//Response.Redirect("login.aspx");
}
%>
答案 0 :(得分:1)
如果您只想将文本写入div,请将div设为runat="server"
属性:
<强> ASPX 强>
<div id="error" runat="server" class="errorMessage"></div>
<强> C#强>
if(IsPostBack && YouHaveAnError) {
error.InnerHtml = "[YourErrorMessage]";
}
答案 1 :(得分:1)
你基本上有几种选择..
1。)将逻辑与标记组合,就像你已经在做的那样(在我看来并不好)
2。)动态添加控件,如下所示:
MyPage.aspx
<asp:Panel id="pnlErrorPlaceHolder" runat="server">
</asp:Panel>
MyPage.aspx.cs
if (i_found_some_error)
{
Label lbl = new Label();
lbl.Text = "An error occurred";
pnlErrorPlaceHolder.Controls.Add(lbl);
}
OR
3。)你可以利用一个名为Visible的属性,它有助于决定控件是否是响应的一部分。这看起来像这样:
MyPage.aspx
<asp:Panel id="pnlErrorBox" Visible="false" runat="server">
Some info for the user if there was an error.
</asp:Panel>
MyPage.aspx.cs
if (there_was_an_error)
{
pnlErrorBox.Visible = true;
// and maybe set some additional info
}
答案 2 :(得分:0)
而不是拥有,你应该有一个asp:Panel,并在后面的代码中切换可见性。
<asp:Panel ID="pnlAccountLocked" Visible="false" runat="server" CSSClass="errorMessage">
Your Account has been locked out. Please wait
<% Response.Write(Session.Timeout); %>
minutes and try again.
<br />
</div>
并在页面加载代码后面的代码中:
private void Page_Load(object sender, System.EventArgs e)
{
pnlAccountLocked.Visible =
!(Session["loginError"].ToString() == "lockout");
}
答案 3 :(得分:0)
我很确定你可以在Page_Load事件处理程序的代码隐藏中执行此操作。有几种方法,但试试这个:
在您的标记中,添加一个Panel控件并最初将其可见性设置为false:
<asp:Panel ID="ErrorPanel" runat="server" Visible="False"></asp:Panel>
然后在您的页面代码隐藏的Page_Load中,执行您的登录逻辑并写入此面板。例如:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Session["loginError"].ToString() == "lockout")
{
LiteralControl errorControl =
new LiteralControl(String.Format("Your account has been locked out. Please wait {0} minutes and try again.", Session.Timeout));
ErrorPanel.Controls.Add(errorControl);
ErrorPanel.Visible = true;
}
// add more login logic for login error
}
catch(Exception) //you may want to capture more specific Exceptions
{
//handle the exception(s)
}
}
答案 4 :(得分:0)
我同意检查ASP.NET MVC,Razor等框架的教程的建议。如果您尝试执行手动验证,那么您已经做错了。有很多很多很多方法可以用很少到零的代码来做到这一点。如果您正在设计Web窗体应用程序,至少可以使用ASP.NET Field Validators。