服务器端警报干扰页面样式

时间:2016-02-08 20:12:51

标签: javascript c# asp.net

我需要在网页上显示一条消息。我使用ASP.Net和C#。我在后端代码中添加了以下代码,以向用户显示消息

protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
    //other code removed for clarity on where and how this alert is triggered
     if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
     {
          Response.Write("<script>alert('Invalid renewal date');</script>");
     }
}

这在事件调用中按预期正常工作。但是,当我单击警报消息上的OK按钮时,文本的字体大小会增加。看起来这个警告信息在页面上打扰了我的风格。

有没有人知道从页面后面的ASP.Net代码显示警报的安全方法?

2 个答案:

答案 0 :(得分:0)

根据您发布的内容很难说出造成字体偏移的原因,但是您的设计可以通过以下方式大大改进:1。不使用服务器调用来验证日期,以及2.不使用alert()锁定整个浏览器,直到有人点击&#34;确定&#34;。

您可以更改在页面加载时在javascript中设置一些变量的方法,然后在输入更改或甚至点击按钮时触发函数。你的检查功能看起来像这样

_memberExpiryDate = new Date('@memberDetails.ExpiryDate.Date'); // or whatever the notation is to write out server variable here

function validate() {
    if (new Date($('#myDateInput').value()) >= _memberExpiryDate.getTime()))
       $('#invalidDateLabel').show();

}

这样您就不会进行不必要的回发,验证可以在用户调整日期时自动更正,并且您的脸上没有任何警报。

您还可以使用Toastr之类的库来显示更优雅的消息,该消息会在几秒钟后消失。但理想情况下,您希望在输入字段旁边显示某些内容,例如asp.net date validator甚至

toastr.error('date is expired');

您也可以使用asp.net range Validator

答案 1 :(得分:-1)

看看是否

<script>setTimeout(function(){alert('Invalid renewal date');},1000);</script>

解决了您的问题

使用ClientRegisterScriptBlock

protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
    //other code removed for clarity on where and how this alert is triggered
     if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
     {
ClientScript.RegisterClientScriptBlock
        ("".GetType(), "s", "<script>alert('Invalid renewal date');</script>");
     }
}

这将在HEAD部分中呈现脚本