locked
Page Handler is Not Triggered RRS feed

  • Question

  • User-190697402 posted

    Hi ,

    Im a having a page with multiple forms inside different tabs.

    Im using page-handlers for inserting form data to database.Onclicking the submit button,it is not even triggering the handler.

    Here is my code,

    Index.cshtml

    <!-- STAFF DETAILS -->
            <div role="tabpanel" class="tab-pane active" id="staffDetails">
                <br />
                <form method="post">
                    <partial name="_StaffDetails" />
                    <div style="float:right">
                        <input type='submit' class='btn btn-success' asp-page-handler="InsertStaffDetails" value='Save' />
                    </div>
                </form>
            </div>

    Index.cshtml.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Contractor_HRMS.Data;
    using Contractor_HRMS.Models;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Mvc.Rendering;
    
    
    namespace Contractor_HRMS.Pages.Staff.Onboarding
    {
        public class IndexModel : PageModel
        {
            private readonly ApplicationDbContext _context;
    
            public IndexModel(ApplicationDbContext applicationDbContext)
            {
                _context = applicationDbContext;
            }
    
            [BindProperty]
            public StaffDetails StaffDetails { get; set; }
    
            [BindProperty]
            public StaffBioData StaffBioData { get; set; }
    
            [BindProperty]
            public StaffEduDetails StaffEduDetails { get; set; }
    
            [BindProperty]
            public StaffAssets StaffAssets { get; set; }
    
            //---Type Of Employee ---//
            public SelectList ShowTypeOfEmployee { get; set; }
    
            //---Employment Type ----//        
            public SelectList ShowEmploymentType { get; set; }
    
            //---Location ----------//        
            public SelectList ContractorLocation { get; set; }
    
            //--- Department -------//        
            public SelectList DeptName { get; set; }
    
            //-------Employment Category --------//        
            public SelectList EmpCategories { get; set; }
    
            //---------Employment Status ---------//        
            public SelectList EmpStatus { get; set; }
    
            //------------Regular/Temporary ----------//       
            public SelectList RegularOrTemporary { get; set; }
    
            // ------------Incentive Plan ----------------//        
            public SelectList IncentivePlans { get; set; }
    
            
    
            //-----------Highest Qualification -------------------//        
            public SelectList Qualification { get; set; }
    
            //-----------Asset Name -------------------//        
            public SelectList ShowAssetName { get; set; }
    
            [BindProperty]
            public string OtherStatus { get; set; }
            public string[] status = new[] { "Yes", "No" };
    
            public void OnGet()
            {
                ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployee", "TypeOfEmployee");
                ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentType", "EmploymentType");
                ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "location", "location");
                DeptName = new SelectList(_context.Department.OrderBy(e => e.DeptName), "DeptName", "DeptName");
                EmpCategories = new SelectList(_context.EmploymentCategory.OrderBy(e => e.EmpCategories), "EmpCategories", "EmpCategories");
                EmpStatus = new SelectList(_context.EmploymentStatus.OrderBy(e => e.EmpStatus), "EmpStatus", "EmpStatus");
                RegularOrTemporary = new SelectList(_context.RegTemp.OrderBy(e => e.RegularOrTemporary), "RegularOrTemporary", "RegularOrTemporary");
                IncentivePlans = new SelectList(_context.IncentivePlan, "IncentivePlans", "IncentivePlans");            
                Qualification = new SelectList(_context.HighestQual, "Qualfication", "Qualfication");
                ShowAssetName = new SelectList(_context.Assets, "assetname", "assetname");
    
            }
    
            public async Task<IActionResult> OnPostInsertStaffDetailsAsync()
            {
                if (ModelState.IsValid)
                {
                    await _context.StaffDetails.AddAsync(StaffDetails);
                    await _context.SaveChangesAsync();
                    return RedirectToPage("/");
    
                }
                else
                {
                    return Page();
                }
            }
        }
    }
    

    Could anyone please let me where im going wrong.

    Monday, November 9, 2020 10:31 AM

Answers

  • User1312693872 posted

    Hi,teenajohn

    teenajohn1989

    Its still showing the form fields from BioData form with Invalid status..

    According to your description, you use GetFieldValidationState("StaffDetails") in OnPostInsertBioDataAsync()?

    The GetFieldValidationState will get the targeted model, if you submit the staffdetails, then ModelState.GetFieldValidationState("StaffDetails")

    will be valid while ModelState.GetFieldValidationState("StaffBioData") will be invalid.

    So you should use like this:

    public async Task<IActionResult> OnPostInsertStaffDetailsAsync()
            {
                ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployees", "TypeOfEmployees");
                ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentTypes", "EmploymentTypes");
                ShowBio = new SelectList(_context.TypeofBios, "TypeOfBios", "TypeOfBios");
    .... if (ModelState.GetFieldValidationState("StaffDetails") == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid) { await _context.StaffDetails.AddAsync(StaffDetails); await _context.SaveChangesAsync(); return Page(); } else { return Page(); } } public async Task<IActionResult> OnPostInsertBioDataAsync() { ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployees", "TypeOfEmployees"); ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentTypes", "EmploymentTypes"); ShowBio = new SelectList(_context.TypeofBios, "TypeOfBios", "TypeOfBios");
    .... if (ModelState.GetFieldValidationState("StaffBioData") == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid) { await _context.StaffBioDatas.AddAsync(StaffBioData); await _context.SaveChangesAsync(); return Page(); } else { return Page(); } }

    Result:you can see, if I submit the stuffdetails, the ModelState.GetFieldValidationState("StaffDetails") will be valid, just input what you want in ( ).

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 11, 2020 6:24 AM

All replies

  • User475983607 posted

    I don't see anything wrong with the code shown.  I don't get the return Page() or redirect but that should not stop the handler from executing.  Just perform basic troubleshooting to find the error in the code.  Open dev tools. Look for errors in the console.  Use the network view to see if there is an HTTP post.  Set a break point in the handler.  Verify client validations are not stopping the post.

    namespace RazorDemo.Pages
    {
        public class IndexModel : PageModel
        {
            public IndexModel() 
            {
    
            }
    
            public void OnGet()
            {
    
            }
    
            public async Task OnPostInsertStaffDetailsAsync()
            {
    
            }
    
            [BindProperty]
            public string Button { get; set; }
            
        }
    }
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <form method="post">
            <div style="float:right">
                <input type='submit' 
                       name="Button" 
                       class='btn btn-success' 
                       asp-page-handler="InsertStaffDetails" 
                       value='Save' />
            </div>
        </form>
        <div>@Model.Button</div>
    </div>

    Monday, November 9, 2020 7:56 PM
  • User-190697402 posted

    Hi mgebhard,

    Thanks for your reply.

    Previously it was not going to the page handler method .

    In my Model class,i have a pagehandler for checking exiting employee id,

    //--- Staff Id ---//
    		[Key]
    		public int StaffID { get; set; }
    
    		//--- Emp Id ---//		
    		[Required(ErrorMessage = "Please enter Employee ID")]
    		[Display(Name = "Employee ID*"),StringLength(100)]
    		//[PageRemote(PageHandler = "IsEmployeeIDUse", HttpMethod = "get")]
    		public string EmpID { get; set; }
    

    when i commented that ,im able to go to the Pagehandler method used for Form submission.

    public async Task<IActionResult> OnPostInsertStaffDetailsAsync()
            {
                if (ModelState.IsValid)
                {
                    await _context.StaffDetails.AddAsync(StaffDetails);
                    await _context.SaveChangesAsync();
                    return Page();
    
                }
                else
                {
                    return Page();
                }
            }

    Now my problem is ModelState.IsValid is always returning false. How can i check the reason for that.

    Upon on from submission i need to navigate to the next tab.

    For that should i use Redirect() or return page() for that.

    Tuesday, November 10, 2020 2:11 AM
  • User475983607 posted

    Now my problem is ModelState.IsValid is always returning false. How can i check the reason for that.

    Set a break point and read the error message.  

    Upon on from submission i need to navigate to the next tab.

    For that should i use Redirect() or return page() for that.

    I don't see any code that opens the next tab.   

    Tuesday, November 10, 2020 3:01 AM
  • User-190697402 posted

    Hi mgebhard,

    What i can see is the values for the fields im using in the next tab is showing invalid. Im not submitting those values though.

    How can i resolve that?

    For moving to next tab do you have any suggestions for that?

    Tuesday, November 10, 2020 3:08 AM
  • User475983607 posted

    What i can see is the values for the fields im using in the next tab is showing invalid. Im not submitting those values though.

    The page model design expects several bound properties.  The page model does not know about the Bootstrap tabs or that you have several forms.  

    How can i resolve that?

    For moving to next tab do you have any suggestions for that?

    Rethink the design.  IMHO, MVC Actions or Web API with AJAX/fetch is a better approach.    

    https://www.mikesdotnetting.com/article/318/working-with-json-in-razor-pages

    https://www.learnrazorpages.com/web-api

    Tuesday, November 10, 2020 3:48 AM
  • User-190697402 posted

    Hi mgebhard,

    The page model design expects several bound properties.  The page model does not know about the Bootstrap tabs or that you have several forms.

    So how i can solve that?Do you have any suggestions for that.

    Tuesday, November 10, 2020 6:11 AM
  • User1312693872 posted

    Hi,teenajohn1989

    Because the ModelState will validate all the models put in razor pages, so the other models will be null when you submit, you can try the

    following code to validate only one model:

    public async Task<IActionResult> OnPostInsertStaffDetailsAsync()
            {
                if (ModelState.GetFieldValidationState("StaffDetails") == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid)
                {
                    await _context.StaffDetails.AddAsync(StaffDetails);
                    await _context.SaveChangesAsync();
                    return Page();
                }
                else
                {
                    return Page();
                }
            }

    Result:

    Best Regards,

    Jerry Cai

    Tuesday, November 10, 2020 8:56 AM
  • User-190697402 posted

    Hi Jerry ,

    Thank you so much for taking your time to explain me the issue in a simple manner.

    I have replaced the if condition and tried,still its not going into the if block and nothing is added to database also.

    when i checked this value

    ModelState.GetFieldValidationState("StaffDetails")
    

    Its still showing the form fields from BioData form with Invalid status..

    Please help me figure out.

    Tuesday, November 10, 2020 9:52 AM
  • User475983607 posted

    When you define [BindProperty] properties, you configured Razor Pages to bind the properties on every post.   This is a fundamental construct and covered in the documentation.

    Another approach is moving the page models to the handler method.  The binding will trigger when the handler is invoked.

        public class TestModel
        {
            [Required]
            public string Name { get; set; }
            public int Number { get; set; }
            public string Button { get; set; }
        }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    using RazorDemo.Configuration;
    using RazorDemo.Models;
    
    namespace RazorDemo.Pages
    {
        public class IndexModel : PageModel
        {
            public IndexModel() 
            {
    
            }
    
            public void OnGet()
            {
    
            }
    
            public async Task OnPostInsertStaffDetailsAsync(TestModel model)
            {
                if (ModelState.IsValid)
                {
                    Message = model.Name;
                }
                else
                {
                    IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
                    Message = allErrors.FirstOrDefault().ErrorMessage;
                }
                
            }
    
            public string Message { get; set; }
            
        }
    }
    
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <form method="post">
            <input name="Name" type="text" value="Hello" />
            <input name="Number" type="text"value="12" />
    
            <div style="float:right">
                <input type='submit'
                       name="Button"
                       class='btn btn-success'
                       asp-page-handler="InsertStaffDetails"
                       value='Save' />
            </div>
        </form>
        <div>@Model.Message</div>
    </div>
    
    
    

    I think you'll continue have issues with the current design approach.  IMHO, there is a lot of JavaScript work left.  An easier design approach is creating separate Razor Pages for each input form.  Tie the page together with navigation.

    Tuesday, November 10, 2020 2:56 PM
  • User-190697402 posted

    Hi mgebhard,

    im using partial view concept, and all these bind properties are using in  separate files.

    This is my Index.cshtml file

    @page
    @model Contractor_HRMS.Pages.Staff.Onboarding.IndexModel
    @{
        ViewData["Title"] = "Staff Onboarding";
        Layout = "~/Pages/Shared/_Layout.cshtml";
    }
    
    <h4>STAFF ONBOARDING</h4>
    <hr />
    
    
    <div id="wizard">
        <!-- Tabstrip -->
        <ul class="nav nav-tabs" role="tablist">
            <li role="presentation" class="nav-item active">
                <a href="#staffDetails" role="tab" class="nav-link" data-toggle="tab">Staff Details</a>
            </li>
            <li role="presentation" class="nav-item">
                <a href="#biodata" class="nav-link" role="tab" data-toggle="tab">Biodata</a>
            </li>
            <li role="presentation" class="nav-item">
                <a href="#eduQualification" class="nav-link" role="tab" data-toggle="tab">Educational Qualification</a>
            </li>
            <li role="presentation" class="nav-item">
                <a href="#assets" class="nav-link" role="tab" data-toggle="tab">Assets</a>
            </li>
            <li role="presentation" class="nav-item">
                <a href="#others" class="nav-link" role="tab" data-toggle="tab">Others</a>
            </li>
            <li role="presentation" class="nav-item">
                <a href="#attachForms" class="nav-link" role="tab" data-toggle="tab">Attachment Of Forms</a>
            </li>
    
        </ul>
        <!-- Tab panes -->
        <div class="tab-content">
    
            <!-- STAFF DETAILS -->
            <div role="tabpanel" class="tab-pane active" id="staffDetails">
                <br />
                <form method="post">
                    <partial name="_StaffDetails" />
                    <div style="float:right">
                        <input type='submit' class='btn btn-success' asp-page-handler="InsertStaffDetails" value='Save' />
                    </div>
                </form>
            </div>
    
            <!-- BIODATA -->
            <div role="tabpanel" class="tab-pane" id="biodata">
                <br />
                <form method="post" asp-page-handler="InsertBioData">
                    <partial name="_BioData" />
                    <div style="float:right">
                        <input type='submit' class='btn btn-success' value='Save' />
                    </div>
                </form>
    
            </div>
    
            <!-- EDUCATIONAL QUALIFICATION -->
            <div role="tabpanel" class="tab-pane" id="eduQualification">
                <br />
                <form method="post" asp-page-handler="InsertEduDetails">
                    <partial name="_EduQualification" />
                    <div style="float:right">
                        <input type='submit' class='btn btn-success' value='Save' />
                    </div>
                </form>
            </div>
    
            <!-- ASSETS -->
            <div role="tabpanel" class="tab-pane" id="assets">
                <br />
                <partial name="_StaffAssets" />
                
            </div>
    
            <!-- OTHERS -->
            <div role="tabpanel" class="tab-pane" id="others">
                <br />
                <form method="post" action="...">
                    <partial name="_Others" />
                    <div style="float:right;">
                        <input type='button' class='btn btn-success' value='Save' />
                    </div>
                </form>
            </div>
    
            <!-- ATTACHMENT OF FORMS -->
            <div role="tabpanel" class="tab-pane" id="attachForms">
                <br />
                <form method="post" action="...">
                    <partial name="_AttachmentOfForms" />
                    <div style="float:right;">
                        <input type='button' class='btn btn-success' value='Save' />
                    </div>
                </form>
            </div>
            @*<div style="float:right">
                    <input type='button' class='btn btn-success' value='Save' />
                </div>
                <div style="float:left">
                    <input type='button' class='btn btn-danger button-previous' value='Back' />
                </div>
                <div style="float:left;margin-left:2px;">
                    <input type='button' class='btn btn-primary button-next' value='Next' />
                </div>*@
        </div>
    </div>
    
    
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

    Index.cshtml.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Contractor_HRMS.Data;
    using Contractor_HRMS.Models;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    
    namespace Contractor_HRMS.Pages.Staff.Onboarding
    {
        public class IndexModel : PageModel
        {
            private readonly ApplicationDbContext _context;
    
            public IndexModel(ApplicationDbContext applicationDbContext)
            {
                _context = applicationDbContext;
            }
    
            [BindProperty]
            public StaffDetails StaffDetails { get; set; }
    
            [BindProperty]
            public StaffBioData StaffBioData { get; set; }
    
            [BindProperty]
            public StaffEduDetails StaffEduDetails { get; set; }
    
            [BindProperty]
            public StaffAssets StaffAssets { get; set; }
    
            //---Type Of Employee ---//
            public SelectList ShowTypeOfEmployee { get; set; }
    
            //---Employment Type ----//        
            public SelectList ShowEmploymentType { get; set; }
    
            //---Location ----------//        
            public SelectList ContractorLocation { get; set; }
    
            //--- Department -------//        
            public SelectList DeptName { get; set; }
    
            //-------Employment Category --------//        
            public SelectList EmpCategories { get; set; }
    
            //---------Employment Status ---------//        
            public SelectList EmpStatus { get; set; }
    
            //------------Regular/Temporary ----------//       
            public SelectList RegularOrTemporary { get; set; }
    
            // ------------Incentive Plan ----------------//        
            public SelectList IncentivePlans { get; set; }
    
            //-----------Gender--------------------------//       
            public SelectList StaffGender { get; set; }
    
            //--------------Religion---------------------//        
            public SelectList StaffReligion { get; set; }
    
            //-----------------Citizenship---------------//        
            public SelectList Citizenship { get; set; }        
            
            //--------------WorkPass Type------------------//        
            public SelectList WorkpassTypeList { get; set; }
    
            //-----------Highest Qualification -------------------//        
            public SelectList Qualification { get; set; }
    
            //-----------Asset Name -------------------//        
            public SelectList ShowAssetName { get; set; }
    
            [BindProperty]
            public string OtherStatus { get; set; }
            public string[] status = new[] { "Yes", "No" };
    
            public void OnGet()
            {
                ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployee", "TypeOfEmployee");
                ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentType", "EmploymentType");
                ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "location", "location");
                DeptName = new SelectList(_context.Department.OrderBy(e => e.DeptName), "DeptName", "DeptName");
                EmpCategories = new SelectList(_context.EmploymentCategory.OrderBy(e => e.EmpCategories), "EmpCategories", "EmpCategories");
                EmpStatus = new SelectList(_context.EmploymentStatus.OrderBy(e => e.EmpStatus), "EmpStatus", "EmpStatus");
                RegularOrTemporary = new SelectList(_context.RegTemp.OrderBy(e => e.RegularOrTemporary), "RegularOrTemporary", "RegularOrTemporary");
                IncentivePlans = new SelectList(_context.IncentivePlan, "IncentivePlans", "IncentivePlans");
                StaffGender = new SelectList(_context.Gender, "StaffGender", "StaffGender");
                StaffReligion = new SelectList(_context.Religion, "StaffReligion", "StaffReligion");
                Citizenship = new SelectList(_context.Citizenship, "Citizenship", "Citizenship");            
                WorkpassTypeList = new SelectList(_context.WorkpassType.OrderBy(e=>e.workpassType), "workpassType", "workpassType");
                Qualification = new SelectList(_context.HighestQual, "Qualfication", "Qualfication");
                ShowAssetName = new SelectList(_context.Assets, "assetname", "assetname");
    
            }
    
            public async Task<IActionResult> OnPostInsertStaffDetailsAsync()
            {
                if(ModelState.GetFieldValidationState("StaffDetails") == ModelValidationState.Valid)
                {
                    await _context.StaffDetails.AddAsync(StaffDetails);
                    await _context.SaveChangesAsync();
                    return Page();
    
                }
                else
                {
                    
                    return Page();
                }
            }
        }
    }

    StaffDetails.cs

    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Contractor_HRMS.Models
    {
        public class StaffDetails
        {
    		//--- Staff Id ---//
    		[Key]
    		public int StaffID { get; set; }
    
    		//--- Emp Id ---//		
    		[Required(ErrorMessage = "Please enter Employee ID")]
    		[Display(Name = "Employee ID*"),StringLength(100)]
    		//[PageRemote(PageHandler = "IsEmployeeIDUse", HttpMethod = "get")]
    		public string EmpID { get; set; }
    
    		//--- Global Id ---//
    		[Display(Name = "Global ID"), StringLength(50)]
    		public string GlobalId { get; set; }
    
    		//--Type of Employee ---//
    		[Required(ErrorMessage = "Please select Type Of Employee")]
    		[Display(Name = "Type Of Employee*"),StringLength(100)]
    		public string TypeOfEmployee { get; set; }
    
    		//--Employment Type ---//
    		[Required(ErrorMessage = "Please select Employment Type")]
    		[Display(Name = "Employment Type*"), StringLength(100)]
    		public string EmploymentType { get; set; }
    
    		//--Employment Category ---//
    		[Required(ErrorMessage = "Please select Employment Category")]
    		[Display(Name = "Employment Category*"), StringLength(50)]
    		public string EmploymentCategory { get; set; }
    
    		//--Employment Status ---//
    		[Required(ErrorMessage = "Please select Employment Status")]
    		[Display(Name = "Employment Status*"), StringLength(50)]
    		public string EmploymentStatus { get; set; }
    
    		//--Regular/Temporary ---//
    		[Required(ErrorMessage = "Please select Regular/Temporary")]
    		[Display(Name = "Regular/Temporary*"), StringLength(50)]
    		public string RegularTemp { get; set; }
    
    		//--Preferred Employee First Name ---//
    		[Required(ErrorMessage = "Please enter Employee First Name(Preferred)")]
    		[Display(Name = "Employee First Name(Preferred)*"), StringLength(100)]
    		public string PreferredEmpFname { get; set; }
    
    		//--Preferred Employee Last Name ---//
    		[Required(ErrorMessage = "Please enter Employee Last Name(Preferred)")]
    		[Display(Name = "Employee Last Name(Preferred)*"), StringLength(100)]
    		public string PreferredEmpLname { get; set; }
    
    		//--Location ---//
    		[Required(ErrorMessage = "Please select Location")]
    		[Display(Name = "Location*"), StringLength(100)]
    		public string Location { get; set; }
    
    		//--Department ---//
    		[Required(ErrorMessage = "Please enter Department")]
    		[Display(Name = "Department*"), StringLength(100)]
    		public string Department { get; set; }
    
    		//--Section ---//
    		[Required(ErrorMessage = "Please enter Section")]
    		[Display(Name = "Section*"), StringLength(100)]
    		public string Section { get; set; }
    
    		//--JobTitle ---//
    		[Required(ErrorMessage = "Please enter JobTitle")]
    		[Display(Name = "JobTitle*"), StringLength(100)]
    		public string JobTitle { get; set; }
    
    		//--Cost Center ---//
    		[Required(ErrorMessage = "Please enter Cost Centre")]
    		[Display(Name = "Cost Centre*"), StringLength(100)]
    		public string CostCentre { get; set; }
    
    		//--Contractor Agency Name ---//
    		[Required(ErrorMessage = "Please enter Contractor Agency Name")]
    		[Display(Name = "Contractor Agency Name*"), StringLength(255)]
    		public string ContractorAgencyName { get; set; }
    
    		//--Start Date ---//
    		[Required(ErrorMessage = "Please select Start Date")]
    		[Display(Name = "Start Date*")]
    		[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    		[DataType(DataType.Date)]
    		public DateTime Startdate { get; set; }
    
    		//--Supervisor Name ---//
    		[Required(ErrorMessage = "Please enter Supervisor Name")]
    		[Display(Name = "Supervisor Name*"), StringLength(255)]
    		public string SupervisorName { get; set; }
    
    		//--Supervisor Email ---//
    		[Required(ErrorMessage = "Please enter Supervisor Email")]
    		[Display(Name = "Supervisor Email*"), StringLength(255)]
    		public string SupervisorEmail { get; set; }
    
    		//--Compensation ---//
    		[Required(ErrorMessage = "Please enter Compensation")]
    		[Display(Name = "Compensation*"), StringLength(50)]
    		public string Compensation { get; set; }
    
    		//--Incentive Plan ---//
    		[Required(ErrorMessage = "Please select Incentive Plan")]
    		[Display(Name = "Incentive Plan*"), StringLength(50)]
    		public string IncentivePlan { get; set; }
    
    		//--Target Incentive ---//
    		[Required(ErrorMessage = "Please enter Target Incentive")]
    		[Display(Name = "Target Incentive*"), StringLength(50)]
    		public string TargetIncentive { get; set; }
    
    		[Display(Name = "Last Modified By")]
    		public string LastModifiedBy { get; set; }
    
    		[Display(Name = "Last Modified TimeStamp")]
    		[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    		public DateTime LastModifiedTimestamp { get; set; }
    		
    
    	}
    }

    _StaffDetails.cshtml

    @model Contractor_HRMS.Pages.Staff.Onboarding.IndexModel
    @*
        For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
    *@
        <div class="row">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="col-6">
                <!-- Type Of Employee -->
                <div class="form-group">
                    <label asp-for="StaffDetails.TypeOfEmployee" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.TypeOfEmployee" asp-items="Model.ShowTypeOfEmployee" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br/>
                    <span asp-validation-for="StaffDetails.TypeOfEmployee" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Employment Type -->
                <div class="form-group">
                    <label asp-for="StaffDetails.EmploymentType" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.EmploymentType" asp-items="Model.ShowEmploymentType" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br/>
                    <span asp-validation-for="StaffDetails.EmploymentType" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Employee Id -->
                <div class="form-group">
                    <label asp-for="StaffDetails.EmpID" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.EmpID" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.EmpID" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Global Id -->
                <div class="form-group">
                    <label asp-for="StaffDetails.GlobalId" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.GlobalId" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.GlobalId" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Employee First Name(Preferred) -->
                <div class="form-group">
                    <label asp-for="StaffDetails.PreferredEmpFname" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.PreferredEmpFname" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.PreferredEmpFname" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Employee Last Name(Preferred) -->
                <div class="form-group">
                    <label asp-for="StaffDetails.PreferredEmpLname" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.PreferredEmpLname" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.PreferredEmpLname" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Location -->
                <div class="form-group">
                    <label asp-for="StaffDetails.Location" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.Location" asp-items="Model.ContractorLocation" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br />
                    <span asp-validation-for="StaffDetails.Location" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Department -->
                <div class="form-group">
                    <label asp-for="StaffDetails.Department" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.Department" asp-items="Model.DeptName" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br />
                    <span asp-validation-for="StaffDetails.Department" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Section -->
                <div class="form-group">
                    <label asp-for="StaffDetails.Section" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.Section" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.Section" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Job-Title -->
                <div class="form-group">
                    <label asp-for="StaffDetails.JobTitle" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.JobTitle" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.JobTitle" class="text-danger" style="margin-left:210px;"></span>
                </div>
            </div>
            <div class="col-6">
                <!-- Cost-Center -->
                <div class="form-group">
                    <label asp-for="StaffDetails.CostCentre" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.CostCentre" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.CostCentre" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Employment-Category -->
                <div class="form-group">
                    <label asp-for="StaffDetails.EmploymentCategory" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.EmploymentCategory" asp-items="Model.EmpCategories" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br />
                    <span asp-validation-for="StaffDetails.EmploymentCategory" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Contractor/Agency Name -->
                <div class="form-group">
                    <label asp-for="StaffDetails.ContractorAgencyName" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.ContractorAgencyName" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.ContractorAgencyName" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Start Date -->
                <div class="form-group">
                    <label asp-for="StaffDetails.Startdate" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.Startdate" class="form-control-staff"/><br />
                    <span asp-validation-for="StaffDetails.Startdate" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Supervisor Name -->
                <div class="form-group">
                    <label asp-for="StaffDetails.SupervisorName" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.SupervisorName" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.SupervisorName" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Compensation -->
                <div class="form-group">
                    <label asp-for="StaffDetails.Compensation" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.Compensation" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.Compensation" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Employment Status -->
                <div class="form-group">
                    <label asp-for="StaffDetails.EmploymentStatus" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.EmploymentStatus" asp-items="Model.EmpStatus" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br />
                    <span asp-validation-for="StaffDetails.EmploymentStatus" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Regular/Temporary -->
                <div class="form-group">
                    <label asp-for="StaffDetails.RegularTemp" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.RegularTemp" asp-items="Model.RegularOrTemporary" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br />
                    <span asp-validation-for="StaffDetails.RegularTemp" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Incentive Plan -->
                <div class="form-group">
                    <label asp-for="StaffDetails.IncentivePlan" class="control-label-staff"></label>
                    <select asp-for="StaffDetails.IncentivePlan" asp-items="Model.IncentivePlans" class="form-control-staff">
                        <option value="">Please Select</option>
                    </select><br />
                    <span asp-validation-for="StaffDetails.IncentivePlan" class="text-danger" style="margin-left:210px;"></span>
                </div>
    
                <!-- Target Incentive -->
                <div class="form-group">
                    <label asp-for="StaffDetails.TargetIncentive" class="control-label-staff"></label>
                    <input asp-for="StaffDetails.TargetIncentive" class="form-control-staff" /><br />
                    <span asp-validation-for="StaffDetails.IncentivePlan" class="text-danger" style="margin-left:210px;"></span>
                </div>
            </div>
        </div>

    Do i need to change this design?Please let me know where im going wrong.

    Wednesday, November 11, 2020 3:37 AM
  • User1312693872 posted

    Hi,teenajohn

    teenajohn1989

    Its still showing the form fields from BioData form with Invalid status..

    According to your description, you use GetFieldValidationState("StaffDetails") in OnPostInsertBioDataAsync()?

    The GetFieldValidationState will get the targeted model, if you submit the staffdetails, then ModelState.GetFieldValidationState("StaffDetails")

    will be valid while ModelState.GetFieldValidationState("StaffBioData") will be invalid.

    So you should use like this:

    public async Task<IActionResult> OnPostInsertStaffDetailsAsync()
            {
                ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployees", "TypeOfEmployees");
                ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentTypes", "EmploymentTypes");
                ShowBio = new SelectList(_context.TypeofBios, "TypeOfBios", "TypeOfBios");
    .... if (ModelState.GetFieldValidationState("StaffDetails") == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid) { await _context.StaffDetails.AddAsync(StaffDetails); await _context.SaveChangesAsync(); return Page(); } else { return Page(); } } public async Task<IActionResult> OnPostInsertBioDataAsync() { ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployees", "TypeOfEmployees"); ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentTypes", "EmploymentTypes"); ShowBio = new SelectList(_context.TypeofBios, "TypeOfBios", "TypeOfBios");
    .... if (ModelState.GetFieldValidationState("StaffBioData") == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid) { await _context.StaffBioDatas.AddAsync(StaffBioData); await _context.SaveChangesAsync(); return Page(); } else { return Page(); } }

    Result:you can see, if I submit the stuffdetails, the ModelState.GetFieldValidationState("StaffDetails") will be valid, just input what you want in ( ).

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 11, 2020 6:24 AM
  • User-190697402 posted

    Hi Jerry

    Jerry Cai

    According to your description, you use GetFieldValidationState("StaffDetails") in OnPostInsertBioDataAsync()?

    No,i used the GetFieldValidationState("StaffDetails") in OnPostInsertStaffDetailsAsync() method only.

    I checked the result in Quick Watch,its showing 'Invalid' 

    Check the below link for the Results View. In that you can see that its still calling other fields from other forms.

    Results View of ModelState("StaffDetails")

    Herewith copy pasting the changes i made in Index.cshtml.cs file

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using DHL_Contractor_HRMS.Data;
    using DHL_Contractor_HRMS.Models;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    
    
    namespace DHL_Contractor_HRMS.Pages.Staff.Onboarding
    {
        public class IndexModel : PageModel
        {
            private readonly ApplicationDbContext _context;
    
            public IndexModel(ApplicationDbContext applicationDbContext)
            {
                _context = applicationDbContext;
            }
    
            [BindProperty]
            public StaffDetails StaffDetails { get; set; }
    
            [BindProperty]
            public StaffBioData StaffBioData { get; set; }
    
            [BindProperty]
            public StaffEduDetails StaffEduDetails { get; set; }
    
            [BindProperty]
            public StaffAssets StaffAssets { get; set; }
    
            [BindProperty]
            public StaffOthers StaffOthers { get; set; }
    
            //---Type Of Employee ---//
            public SelectList ShowTypeOfEmployee { get; set; }
    
            //---Employment Type ----//        
            public SelectList ShowEmploymentType { get; set; }
    
            //---Location ----------//        
            public SelectList ContractorLocation { get; set; }
    
            //--- Department -------//        
            public SelectList DeptName { get; set; }
    
            //-------Employment Category --------//        
            public SelectList EmpCategories { get; set; }
    
            //---------Employment Status ---------//        
            public SelectList EmpStatus { get; set; }
    
            //------------Regular/Temporary ----------//       
            public SelectList RegularOrTemporary { get; set; }
    
            // ------------Incentive Plan ----------------//        
            public SelectList IncentivePlans { get; set; }
    
            //-----------Gender--------------------------//       
            public SelectList StaffGender { get; set; }
    
            //--------------Religion---------------------//        
            public SelectList StaffReligion { get; set; }
    
            //-----------------SGCitizenship---------------//        
            public SelectList Citizenship { get; set; }
    
            
            
            //--------------WorkPass Type------------------//        
            public SelectList WorkpassTypeList { get; set; }
    
            //-----------Highest Qualification -------------------//        
            public SelectList Qualification { get; set; }
    
            //-----------Asset Name -------------------//        
            public SelectList ShowAssetName { get; set; }
    
            //----------------Othes--------------------------//
            public string[] status = new[] { "Yes", "No" };
    
            public void OnGet()
            {
                ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployee", "TypeOfEmployee");
                ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentType", "EmploymentType");
                ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "location", "location");
                DeptName = new SelectList(_context.Department.OrderBy(e => e.DeptName), "DeptName", "DeptName");
                EmpCategories = new SelectList(_context.EmploymentCategory.OrderBy(e => e.EmpCategories), "EmpCategories", "EmpCategories");
                EmpStatus = new SelectList(_context.EmploymentStatus.OrderBy(e => e.EmpStatus), "EmpStatus", "EmpStatus");
                RegularOrTemporary = new SelectList(_context.RegTemp.OrderBy(e => e.RegularOrTemporary), "RegularOrTemporary", "RegularOrTemporary");
                IncentivePlans = new SelectList(_context.IncentivePlan, "IncentivePlans", "IncentivePlans");
                StaffGender = new SelectList(_context.Gender, "StaffGender", "StaffGender");
                StaffReligion = new SelectList(_context.Religion, "StaffReligion", "StaffReligion");
                Citizenship = new SelectList(_context.SGCitizenship, "Citizenship", "Citizenship");
                
                WorkpassTypeList = new SelectList(_context.WorkpassType.OrderBy(e=>e.workpassType), "workpassType", "workpassType");
                Qualification = new SelectList(_context.HighestQual, "Qualfication", "Qualfication");
                ShowAssetName = new SelectList(_context.Assets, "assetname", "assetname");
    
            }
    
            public async Task<IActionResult> OnPostInsertStaffDetailsAsync()
            {
                ShowTypeOfEmployee = new SelectList(_context.TypeOfEmployees, "TypeOfEmployee", "TypeOfEmployee");
                ShowEmploymentType = new SelectList(_context.EmploymentTypes, "EmploymentType", "EmploymentType");
                ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "location", "location");
                DeptName = new SelectList(_context.Department.OrderBy(e => e.DeptName), "DeptName", "DeptName");
                EmpCategories = new SelectList(_context.EmploymentCategory.OrderBy(e => e.EmpCategories), "EmpCategories", "EmpCategories");
                EmpStatus = new SelectList(_context.EmploymentStatus.OrderBy(e => e.EmpStatus), "EmpStatus", "EmpStatus");
                RegularOrTemporary = new SelectList(_context.RegTemp.OrderBy(e => e.RegularOrTemporary), "RegularOrTemporary", "RegularOrTemporary");
                IncentivePlans = new SelectList(_context.IncentivePlan, "IncentivePlans", "IncentivePlans");
    
                if (ModelState.GetFieldValidationState("StaffDetails") == ModelValidationState.Valid)
                {
                    await _context.StaffDetails.AddAsync(StaffDetails);
                    await _context.SaveChangesAsync();
                    return Page();
                }
                else
                {                
                    return Page();
                }
            }
        }
    }
    

    Wednesday, November 11, 2020 7:25 AM
  • User1312693872 posted

    Hi,teenajohn1989

    It's strange, my code is the same as yours and works fine. It doesn't matter whether the other forms' field are invalid or not, it will only judge

    the StaffDetails' required properties.

    Then, can you tell me your:

    • Browser version and whether you have enabled the javascript(your validation can work?)
    • Asp.net core version
    • How did you tested your code? Have you input all the required properties? 

    Best Regards,

    Jerry Cai

    Wednesday, November 11, 2020 9:05 AM
  • User-190697402 posted

    Hi Jerry,

    Jerry Cai

    • Browser version and whether you have enabled the javascript(your validation can work?)
    • Asp.net core version
    • How did you tested your code? Have you input all the required properties? 

     

    My Browser is FireFox Version 80.0.1,Javascript is enabled and my javascript functions were working fine.

    Asp.net Core Version .Net Core 3.1

    Yes i have input all the required fields of StaffDetails page

    Even i checked in Google Chrome also,Same problem i have there.

    Is it because of my dropdownlist??

    Wednesday, November 11, 2020 9:23 AM
  • User475983607 posted

    im using partial view concept, and all these bind properties are using in  separate files.

    Exactly!   You need to fix the design.  Your partials accept the entire Index Page model.  Partials are intended to be reusable.  Your design makes the partial dependent on the main Razor Page model.  Your Partials can only be used in the Index page.  Partials are supposed to have their own model so they can be used in any page.  

    Your design is half way between a Single Page Application and Razor Pages.  It seems your main design intent is to do partial updates using full page posts to Razor Page handlers.  Well, this is very difficult task due to the Razor Page life cycle.   Like Partials, you are not using Razor Pages as intended either.

    IMHO, you need to make a design decision.  If you want to go with partial updates then design the application to use AJAX/fetch with Web API or a page handler.  Each tab has its own AJAX/fetch post and you'll need to write code that updates the UI when the request returns to the AJAX/fetch code.  

    If you want to go with Razor Pages then create a Razor Page for each form.  You can still use tabs or whatever UI you like.  The only difference with this approach is the each Razor Page handles its own Page Models and clicking a tab will cause an HTTP Get.  However, this will fix the model binding and validation issues.

    Wednesday, November 11, 2020 2:01 PM
  • User-190697402 posted

    Hi Mgebhard,

    If you want to go with partial updates then design the application to use AJAX/fetch with Web API or a page handler

    im using page handler method.

    am i doing anything wrong in my code?

    Thursday, November 12, 2020 1:01 AM
  • User-190697402 posted

    Hi Jerry Cai and Mgebhard,

    Is there anyother way to validate only one model?

    Most of the forum post is using this method.

    ModelState.GetFieldValidationState("String")

    Is there anyway to ouput the Modelstate errors.?

    Appreciate your help in this, as i am stuck in this part for almost 2 days.

    Thursday, November 12, 2020 2:53 AM
  • User-190697402 posted

    Hi Jerry Cai,

    Finally i figured out what was the issue.

    I missed out to include one input field in my design and in my models i declared it as a required field.

    Now it is inserting values into database for Staff Details Form.

    Thank you so much Jerry!

    Thursday, November 12, 2020 7:44 AM