Search code examples
c#asp.netcode-behind

Validate form on server side


I am working in asp.net 4.0 Is there any way to check on server side that if we are leaving the page and redirecting the control to another page, then check on the current form, is there any field that is modified? If yes, then first save that record and then redirect to the new page. Is there any way to check this on server side? (Code behind file)


Solution

  • Ah I see. As an example lets assume you have a User Class which you will use to display your page form in question

    public class User
        {
            public int Id { get; set; }
            public string Username { get; set; }
            public string Address { get; set; }
        }
    

    on page load event load this object with relevent values and they use the loaded object to display the page form. Lets call this object "LoadedUser"

    After the user click on the redirect link you need to handle that event (which I know your doing) and in this event create a new User object using the current values on the page form and then lets call this object "NewLoadedUser" now we are going to compare the LoadedUser with NewLoadedUser object by using IEquatable interface.

    So go ahead and add this to the user class

    public class User: IEquatable<User>
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public string Address { get; set; }
    
        public override int GetHashCode()
        {
            return Id ^ Id.GetHashCode(); // or whatever
        }
    
        public override bool Equals(object other)
        {
            return this.Equals(other as User);
        }
    
        public bool Equals(User other)
        {
            return (other != null &&
                    other.Id == this.Id &&
                    other.Username == this.Username &&
                    other.Address == this.Address );
        }
    }
    

    After doing this in your code you should be able to compare the two objects like this.

    bool areEqual = NewLoadedUser.Equals(LoadedUser);
    

    and then you can use the areEqual bool flag to update the record or not.

    Hope this helps