Search code examples
asp.net-corerazor-pages

Remote Validation in Asp.Net Core Razor Pages


I’m developing a web application using Razor Pages and Code First.

I know that in ASP.NET MVC, you can use Remote above a property referring to an action in a controller that validates the data without the whole page being posted back. But it doesn’t seem to work in Razor Pages as there’s no Controller and Action in ASP.NET Core Razor Pages.

So, How can I get remote validation done in Razor Pages?


Solution

  • I added the following in my model class:

     [Remote(action: "IsNationalIdValid",controller:"Validations")]
    

    I created 'Controllers' folder in my Razor Pages project and added a controller(ValidationsController) with the following method:

            public IActionResult IsNationalIdValid(string nationalId){}
    

    However,when I tried to go to the page where this validation was supposed to work,I got the following exception:

    No URL for remote validation could be found in asp.net core

    Thanks to a reply to the same thread in Asp.Net forum,I figured out the answer: All I needed to do was to add the following code in Startup.cs file of my Razor Pages project in order to configure the route.

    app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
    

    Hope this answer will help someone else as well.