我在尝试使用asp.net表单上的Label control
显示错误消息时收到错误
我想做的事情:
如果用户点击Submit button
而未选择dropdown control
和textbox control
中提供的选项,我想使用Label控件显示错误消息。
我做了什么:
我已将代码放在.aspx上lblControl.Visible="true"
,而aspx.cs上的代码位于Page_load- if(!isPostBack){ lblControl.Visible="false";
然后我处理了click->
if((txtbox.Text == "") & (ddlbox.SelectedItem.Text == "Select"))
{
string Message = "Please select a value in drop down list, other than 'Select' and fill some value in text box.";
lblControl.Visible = true;
lblControl.Text = Message;
/* I have tried this one code also
Page.ClientScript.RegisterStartupScript(this.GetType(), "errMsg", script, true); //doesn't help */
}
else{
save(); //another method to perform insert operation.
}
现在发生了什么:(根据我的调试观察) 每当我尝试以Label(控件)的形式显示错误消息时。程序流程转到主页面,而不是显示错误消息。
At the master we have placed various links related to show `logo image, ` logout link` etc `inside <%=Page.ResolveUrl("~/Modules.aspx")%>`
从那里开始,debugging
停止了&amp;页面已呈现,但没有lblContorl
的消息。
混淆与问题:我无法理解此代码切换(将子页面转换为母版页的代码流程)
非常感谢所有类型的建议!答案 0 :(得分:1)
尝试以下方法:
将您的代码更改为:
if(String.IsNullOrWhiteSpace(txtbox.Text) || ddlbox.SelectedItem.Text == "Select")
{
string message = "Your Error Message";
lblControl.Text = message;
lblControl.Visible = true;
return; // optional
}
else
{
save(); //another method to perform insert operation.
}
这样做的是,如果一个或两个语句都为真,则执行此代码。如果您不想在此之后运行任何其他代码,请添加&#39; return;&#39;在if语句的最后一行代码之后。
在ASP.Net中显示错误的另一种方法是使用 ValidationSummary 。
有了这个,你不必担心控制是否可见。 只需在您的页面上添加ValidationSummary,就像您现在的标签一样 -
<asp:ValidationSummary runat="server" ID="myValidationSummary" CssClass="my-error-class" />
并将您的代码更改为:
if(String.IsNullOrWhiteSpace(txtbox.Text) || ddlbox.SelectedItem.Text == "Select")
{
string message = "Your Error Message";
ModelState.AddModelError("", message);
return;
}
else
{
save(); //another method to perform insert operation.
}
这样,就不需要处理可见性了,你也可以将它用于DataBound控件,因此可能值得研究。
编辑:要使用ModelState,您需要导入ModelBinding。只需添加:
using System.Web.ModelBinding;
到你的页面。你甚至可以通过简单地调用
在UserControls中使用它Page.ModelState.AddModelError("","Your Error Message");
您应该可以在ASP.NET中使用它而不会出现任何问题。
我无法理解这个代码转换(获取子代码的代码流) 页面到母版页)
请参阅this Link以了解ASP页面生命周期。