Search code examples
asp.net.netvb.netrazorasp.net-webpages

ASP.NET Web Pages (Razor) Exit Code Block


Does anybody know how to exit a code block without interrupting page load in ASP.NET Web Page (Razor) in VB language? Let's say I have a login mechanism that execute in the following order:

Before page load:

  1. Check if user id exist.
  2. Check if password match.

if the user id does not exist, display error message then skip password validation and let the rest of the html page (body, footer) load. My current solution is to use VB specific GoTo.. statement which I think is ugly. Does anybody has a more elegant solution? Below is a simple sample code:

@Code
dim login As New clsLogin 'assume this class handles login validation
dim inputUserID As String 'this variable hold user id entered by user
dim inputPwd As String 'this is password entered by user

'First, check if that ID exist in database
if login.userExist(inputUserID) = false then
    @<p>User does not exist !</p>
    GoTo skip
End If

'If ID exist, check if password match
if login.checkPwd(inputUserID, inputPwd) = false then
    @<p>Password Mismatch !</p>
    GoTo skip
End If

'Passes all validation, display success message
@<p>Login Successful !</p>

skip:
End Code

I tried to replace the GoTo statement with return statement. However, it also stopped the page loading. I put the validation server code before any HTML is displayed and if I use return statement it wont show the HTML page. Any idea? Thanks in advance.


Solution

  • Short answer could use a function:

    @Functions
    
    
    function Check(byval inputUserID as integer, byval inputPwd as string) as string
    dim login As New clsLogin 'assume this class handles login validation
    dim result as string = string.Empty
    
    'First, check if that ID exist in database
    if login.userExist(inputUserID) = false then
        return "User does not exist !"
    
    End If
    
    
    'If ID exist, check if password match
    if login.checkPwd(inputUserID, inputPwd) = false then
        return "Password Mismatch !"
    End If
    
    return result
    
    end function
    End functions
    
    @Code
    
    dim inputUserID As String 'this variable hold user id entered by user
    dim inputPwd As String 'this is password entered by user
    
    dim msg = @Check(inputUserID,inputPwd)
    'Passes all validation, display success message
    if string.isnullorempty(msg) then
        msg = "<p>Login Successful !</p>"
    
    end if
    @msg
    End Code
    

    Hoever reading your comment seems you are looking for an elegant and sustainable solution, so I think you could approach your problem with a loosely coupled ValidationManager:


    VB (translated with Telerik code converted)


    Public Interface ILoginProvider
        Function UserExist(inputUserID As Integer) As Boolean
        Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
    End Interface
    
    Public Class LoginProvider
        Implements ILoginProvider
        Public Function UserExist(inputUserID As Integer) As Boolean
            Return True
        End Function
        Public Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
            Return True
        End Function
    End Class
    
    Public Class ValidationResult
        Public Property Result() As Boolean
            Get
                Return m_Result
            End Get
            Set
                m_Result = Value
            End Set
        End Property
        Private m_Result As Boolean
        Public Property ResultMessage() As String
            Get
                Return m_ResultMessage
            End Get
            Set
                m_ResultMessage = Value
            End Set
        End Property
        Private m_ResultMessage As String
    End Class
    
    Public MustInherit Class Validator
        Protected _provider As ILoginProvider
        Protected _inputUserID As Integer
        Protected _inputPwd As String
    
        Public Sub New(provider As ILoginProvider, inputUserID As Integer, inputPwd As String)
            _provider = provider
            _inputPwd = inputPwd
    
            _inputUserID = inputUserID
        End Sub
        Public MustOverride Function Validate() As ValidationResult
    End Class
    
    Public Class UserExistenceValidator
        Inherits Validator
        Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)
    
            MyBase.New(provider, inputUserID, inputPwd)
        End Sub
    
        Public Overrides Function Validate() As ValidationResult
            Dim result = New ValidationResult()
            Dim check = _provider.UserExist(_inputUserID)
            result.Result = check
            If Not check Then
                result.ResultMessage = "User Doesn't exist"
            End If
    
            Return result
        End Function
    End Class
    
    Public Class UserPasswordValidator
        Inherits Validator
        Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)
    
            MyBase.New(provider, inputUserID, inputPwd)
        End Sub
    
        Public Overrides Function Validate() As ValidationResult
            Dim result = New ValidationResult()
            Dim check = _provider.CheckPwd(_inputUserID, _inputPwd)
            result.Result = check
            If Not check Then
                result.ResultMessage = "Wrong Password"
            End If
    
            Return result
        End Function
    End Class
    
    Public Class ValidationManager
        Private _validators As List(Of Validator)
        Public Sub New()
            _validators = New List(Of Validator)()
        End Sub
    
        Public Function Validate() As ValidationResult
            Dim result As ValidationResult = Nothing
            For Each item As var In _validators
                result = item.Validate()
                If Not result.Result Then
                    Return result
                End If
            Next
    
            Return New ValidationResult() With { _
                Key .Result = True, _
                Key .ResultMessage = "Successfull validated" _
            }
        End Function
    End Class
    

    C#


      public interface ILoginProvider
      {
        bool UserExist(int inputUserID);
        bool CheckPwd(int inputUserID, string inputPwd);
      }
    
      public class LoginProvider: ILoginProvider
      {
        public bool UserExist(int inputUserID)
        {
          return true;
        }
        public bool CheckPwd(int inputUserID, string inputPwd)
        {
          return true;
        }
      }
    
      public class ValidationResult
      {
        public bool Result { get; set; }
        public string ResultMessage { get; set; }
      }
    
      public abstract class Validator
      {
        protected ILoginProvider _provider;
        protected int _inputUserID; 
        protected string _inputPwd;
    
        public Validator(ILoginProvider provider, int inputUserID, string inputPwd)
        {
          _provider = provider;
          _inputPwd = inputPwd;
          _inputUserID = inputUserID;
    
        }
        public abstract ValidationResult Validate();
      }
    
      public class UserExistenceValidator : Validator
      {
        public UserExistenceValidator(LoginProvider provider,int inputUserID, string inputPwd): base(provider,inputUserID, inputPwd)
        {
    
        }
    
        public override ValidationResult Validate()
        {
          var result = new ValidationResult();
          var check = _provider.UserExist(_inputUserID); 
          result.Result = check;
          if(!check)
            result.ResultMessage = "User Doesn't exist";
    
          return result;
        }
      }
    
      public class UserPasswordValidator : Validator
      {
        public UserPasswordValidator(LoginProvider provider, int inputUserID, string inputPwd)
          : base(provider, inputUserID, inputPwd)
        {
    
        }
    
        public override ValidationResult Validate()
        {
          var result = new ValidationResult();
          var check = _provider.CheckPwd(_inputUserID, _inputPwd);
          result.Result = check;
          if (!check)
            result.ResultMessage = "Wrong Password";
    
          return result;
        }
      }
    
      public class ValidationManager
      {
        List<Validator> _validators;
        public ValidationManager()
        {
          _validators = new List<Validator>();
        }
    
        public ValidationResult Validate()
        {
          ValidationResult result = null;
          foreach (var item in _validators)
          {
            result = item.Validate();
            if(!result.Result)
              return result;
          }
    
          return new ValidationResult(){Result = true,ResultMessage="Successfull validated" };
        }
      }
    

    Use


    @Function Check() As string
    
      Dim login As New clsLogin 'assume this class handles login validation
      Dim inputUserID As String 'this variable hold user id entered by user
      Dim inputPwd As String 'this is password entered by user
    
    
      Dim login As New LoginProvider()
      Dim validators = New List(Of Validator)()
      validators.Add(New UserExistenceValidator(login, 1, "test1"))
      validators.Add(New UserPasswordValidator(login, 1, "test1"))
    
      Dim manager = New ValidationManager(validators)
      Dim result = manager.Validate()
      return string.format("<p>{0}</p>",result.ResultMessage)
    
    
     End Function
    
    
      @Code
    
        @Check()
    
      End Code