Dave
Dave

Reputation: 253

Call a method in a CORE Razor Page from a ViewModel

My Razor Page

   public class IndexModel : BaseModel {
        public void OnGet() {
            BaseModelMethod();
        }
        public void LocalMethod() {}
   }

calls a method in the base ViewModel

public class BaseModel : PageModel {
    public void BaseModelMethod() {
        // Do stuff 
    }
}

Is there a way to call back to the instance of LocalMethod in the calling Razor Page?

Upvotes: 1

Views: 208

Answers (1)

pitaridis
pitaridis

Reputation: 2983

You have to define the function as a virtual function. Your BaseModel has to have the following form:

public class BaseModel : PageModel
{
    public void BaseModelMethod()
    {
        LocalMethod();
    }

    public virtual void LocalMethod()
    {

    }
}

As you can see I creted the virtual function so that we will know what we kind of method we will call.

Now we can define our own version of LocalMethod like this:

public class IndexModel : BaseModel
{
    public void OnGet()
    {
        BaseModelMethod();
    }

    public override void LocalMethod()
    {
        base.LocalMethod();
    }
}

Upvotes: 1

Related Questions