选项1:使用验证控制
解决这个最简单的方法是使用一个RegularExpressionValidator控件来比较值。
标记片段:
<asp:Label ID="lblName" runat="server" Text="Name: " />
<asp:TextBox ID="txtName" runat="server" />
<asp:RegularExpressionvalidator ID="valName" runat="server" ControlToValidate="txtName" ErrorMessage="You must change the name before saving" Display="Dynamic" />
<asp:Button ID="btnSaveAs" runat="server" OnClick="btnSaveAs_Click" Text="Save As" CausesValidation="True" />
在您的代码隐藏一旦表单字段(专辑名称等)结合,运行此:
valName.ValidationExpression = string.Format("[^{0}]", Regex.Escape(lblName.Text));
上述正则表达式将是有效的除了开始之外的任何输入。如果用户更改相册名称的文本,保存按钮将正确验证。如果他们不这样做,验证者会在页面上显示一条消息,说他们必须更改它。
然后处理OnClick
事件保存按钮只为保存价值,因为如果网页被验证它只会火:
protected void btnSaveAs_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//do you save actions as needed
}
}
您仍然可以使用您的确认框,你想要的,由做:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you wish to change the name?');";
}
上面应该工作得很好。另一种方法是列举如下:
选项2:如果你想彻底做验证客户端使用客户端验证功能
,你可以但它会复杂得多。你需要做的是注册一个完全客户端验证功能。
在后面的代码Page_PreRender期间:
protected void Page_PreRender(object sender, EventArgs e)
{
//define the script
string script = @"
function validateAlbumName(oldName, textBoxId) {
//get the textbox and its new name
var newName = document.GetElementById(textBoxId).value;
//compare the values
if (newName === oldName) {
//if the name hasn't changed,
alert('You must change the name of the album');
return false;
}
return confirm ('Are you sure you want to save the playlist ' + newName);
}
";
//register the client script, so that it is available during the first page render
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SaveAsValidation", script);
//add the on client click event, which will validate the form fields on click the first time.
btnSaveAs.OnClickClick = string.Format("return validateAlbumName('{0}','{1}');", txtAlbumName.Text, txtAlbumName.ClientID);
}
希望这有助于。上面可能有一些语法错误,因为我只是很快将它们扔在一起..
Xaisoft,我在下面的答案中付出了相当多的努力。如果您发现它是正确和有用的,请确保您将其标记为答案。 – 2009-12-16 17:44:14
对不起,我还没有机会测试它。我会稍微。一旦我做了,我会标记它。 – Xaisoft 2009-12-16 19:54:13