techspider February 2016

Server side alert disturbs page styling

I needed to show a message on web page. I'm using ASP.Net and C#. I added below code in the back-end code to show message to the user

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>");
     }
}

This works fine as expected on the event call. But, the moment I click OK button on the alert message, the font-size of the text increases. It looks like somehow this alert message is disturbing my styles on the page.

Does anyone know a safe method to display alert from ASP.Net code behind page?

Answers


Dave Bush February 2016

See if

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

fixes your issue

Using 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>");
     }
}

This renders the script in the HEAD section


Sonic Soul February 2016

It is hard to tell what is causing the font shift based on what you posted, but your design can be vastly improved by 1. not making a server call just to validate a date, and 2. not using alert() which locks the whole browser until someone clicks "ok".

You could change your approach to set a few variables in javascript on page load, and then trigger a function on say change of your input or even on button click. your check function could look something like this

_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();

}

this way you're not making unnecessary postbacks, validation can autocorrect as users adjust dates, and there are no alerts in your face.

you can also use a library such as Toastr to show a more graceful message which disappears after a few seconds. but ideally you want to show something right next to the input field like asp.net date validator even

toastr.error('date is expired');

Also you could just use the asp.net range Validator.

Post Status

Asked in February 2016
Viewed 3,981 times
Voted 10
Answered 2 times

Search




Leave an answer