Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 427
Meisam Dehghan Avatar asked Dec 06 '22 10:12

Meisam Dehghan


2 Answers

For anyone like me who finds this later and loses their mind trying to pass a property from their model onto the validation method, make the method signature look like so

public IActionResult IsCharacterNameAvailable([Bind(Prefix = "Character.Name")] string name)

Character is the model and Name is the property. Without adding the [Bind(Prefix = "")] before the parameter I was always receiving a null value. Hope this helps!

like image 107
Nekko Rivera Avatar answered Jan 05 '23 01:01

Nekko Rivera


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.

like image 22
Meisam Dehghan Avatar answered Jan 04 '23 23:01

Meisam Dehghan