Home > Mobile >  does razor page have onLoad method?
does razor page have onLoad method?

Time:01-06

I know there is get and post method in razor page but what if you want you load some code soon as page is loads up? do I use a constructor method?

 public async Task<IActionResult> OnGetAsync()
        {
            return Page();
        }

        public async Task<IActionResult> OnPostAsync(){
           return Page();
       }

CodePudding user response:

Do you mean you want to use depedency injection?If so,you can try to use a constructor method.Firstly,you need to register a service in Program.cs,and then use a constructor in your pagemodel.

ICommentService:

public interface ICommentService
    {
        string Test();
    }

CommentService:

public class CommentService : ICommentService
    {
        public string Test()
        {
            return "Test";
        }
    }

pageModel:

public class TestdModel : PageModel
    {
        private readonly ICommentService _commentService;
        public TestdModel (ICommentService commentService)
        {
            _commentService = commentService;
        }
    }

Then you can use _commentService in your pagemodel.

  • Related