Home > Net >  Razor pages client site validation not working
Razor pages client site validation not working

Time:07-20

I'm trying to use client-side validation in my razor pages app but it's not working for the views.

It does work on the register page that is located under the identity area.

Create.cshtml

@model Toolbox.Models.ProjectsModel.Assignment

@{
    ViewData["Title"] = "Create";
}

<h1>Nieuwe taak maken</h1>

<h4>Taak</h4>
<hr />
<div >
    <div >
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" ></div>
            <div >
                <label asp-for="Name" ></label>
                <input asp-for="Name"  />
                <span asp-validation-for="Name" ></span>
            </div>
            <div >
                <label asp-for="Fase" ></label>
                <input asp-for="Fase"  />
                <span asp-validation-for="Fase" ></span>
            </div>
            <div >
                <input type="submit" value="Maak nieuwe taak" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index" >Terug</a>
</div>

Assignment.cs

using System.ComponentModel.DataAnnotations;
using Toolbox.Interfaces;

namespace Toolbox.Models.ProjectsModel
{
    public class Assignment : IAssignment
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Naam")]
        [Required]
        public string Name { get; set; }
        [Required]
        public string Fase { get; set; }

        public List<SubAssignment> SubAssignment { get; set; }
    }
}

_ViewImports.cshtml

@using Toolbox
@using Toolbox.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

_viewStart.cshtml

@{
    Layout = "_Layout";
}

Program.cs

    app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(name: "default",
    pattern: "{controller=Home}/{action=Index}");
    endpoints.MapRazorPages();
});

Does anybody know how I need to solve this problem?

CodePudding user response:

You need to include the _ValidationScriptsPartial file in the Razor page. Add the following to the bottom of the page/view:

@section scripts{
    <partial name="_ValidationScriptsPartial" />
}

CodePudding user response:

If you add these scripts the validation will work but if you want to use jquery.

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
  • Related