Postback from javascript - the right way

January 31st, 2008

Sometimes a programmer must do very weird things in his ASP.NET webapp. Among them, there is a postback initiated in custom javascript. Before .NET Framework 2.0, it was no good solution to achieve it. Fortunately it can be done without much effort nowadays.

There is an interface called IPostBackEventHandler which must be implemented by a page or a control. Then you must create javascript containing reference to postback function retrieved by ClientScriptManager.GetPostBackEventReference(...) method.

The sample web control's codebehind can look like below:

C#:
public class MyControl : Control, IPostBackEventHandler
{
    // this method will be called on postback initiated in javascript
    public void RaisePostBackEvent(string eventArgument)
    {
        if (eventArgument == "foo")
        {
            // do something
        }
    }
}

then we create javascript in aspx / ascx file:

ASP:
<script>
function Test()
{
    <%= Page.ClientScript.GetPostBackEventReference(this, "foo"); %>
}
</script>

Now, when a Test() function is called in a browser, our page will do a nice, clean postback :)

Code masters ;)

October 26th, 2007

Every coder sometimes encounters a situation when a bug must be fixed. At the begining it looks for a very easy task... but the code reveals that it might be quite tricky ;) Here is one of most common antipattern - hardcoding mixed with magic numbers. Please fasten your seatbelts :D

C#:
EditorDatabase EditorDB = new EditorDatabase();
if (UserIDTextBox.Text == "0" && LoginRoleDropDownList.SelectedValue == "11")
{
    EditorDB.Save(CodeHiddenField.Value, TextGridView.Rows[rowID].Cells[5].Text,
    System.Convert.ToInt32(TextGridView.Rows[rowID].Cells[10].Text), TextGridView.Rows[rowID].Cells[8].Text,
    0, spr, TextGridView.Rows[rowID].Cells[11].Text).ExecuteNonQuery();
}
else
{
    EditorDB.Save(CodeHiddenField.Value, TextGridView.Rows[rowID].Cells[5].Text,
    System.Convert.ToInt32(TextGridView.Rows[rowID].Cells[10].Text), TextGridView.Rows[rowID].Cells[8].Text,
    System.Convert.ToInt32(UserDropDownList.SelectedValue), spr, TextGridView.Rows[rowID].Cells[11].Text).ExecuteNonQuery();
}

UserControl in Dll

March 20th, 2007

Great feature of ASP.NET is that we are able to write a server control, pack it into assembly and use in many applications. However, it is quite hard to create one. On the other hand, user controls (ascx) are very easy to write but they're not so good to reuse because we must share our code.

Read the rest of this entry »

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!