简体   繁体   中英

Show validation messages on partial views in asp.net core MVC

I have the following model in order to show validations on multiselect list

using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace AccountManagementUI.Models
{
    public class NewMembersAddViewModel
    {
        public string GroupId { get; set; }
        public string GroupName { get; set; }
        public List<SelectListItem> membersList { get; set; }
        [Required(ErrorMessage ="Please select atlast 1 employee")]
        public List<Guid> selectedMembersId { get; set; }
    }
}

My Controller post method is as follows:

[HttpPost]
        public IActionResult GetNewMembers(NewMembersAddViewModel groupMemberData)
        {
            if (ModelState.IsValid)
            {
                AddMembersToGroup addMembersToGroup = new AddMembersToGroup();
                addMembersToGroup.GroupId = groupMemberData.GroupId;
                foreach (var memberId in groupMemberData.selectedMembersId)
                {
                    addMembersToGroup.UserIds.Add(memberId.ToString());
                }
                _gateway.AddMembersToGroup(addMembersToGroup);
                return RedirectToAction("GroupMembers", "Group", new { groupId = groupMemberData.GroupId });
            }
            else
            {
                return PartialView("_GetNewMembers", groupMemberData);
            }
            
        }

My view is as below:

@model AccountManagementUI.Models.NewMembersAddViewModel
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Active Directory Management Portal</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="" />
    <meta name="keywords" content="" />

    <!-- Latest compiled and minified CSS -->
    <!-- Pagelevel Initializations Of Plugins -->
</head>
<body>
        <form class="console-panel grid-stack-item-content" asp-action="GetNewMembers" asp-controller="Group" method="post">
        <input type="hidden" asp-for="GroupId" />
        <input type="hidden" asp-for="GroupName" />
        <div class="console-panel-body pl-0 pr-0">
            <div class="console-form-body ">
                <div class="row">
                    <div class="col-lg-12 col-md-12">
                        <div class="form-group row">
                            <label class="col-2 col-form-label">Members</label>
                            <div class="col-10">
                                <select asp-for="selectedMembersId" asp-items="Model.membersList" multiple="multiple" placeholder="Select Members" onchange="console.log($(this).children(':selected').length)" class="search-box form-control">
                                </select>
                                <span asp-validation-for="selectedMembersId" class="text-danger"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="console-footer">
            <button class="btn btn-sm btn-info" type="submit">Submit</button>
            <a id="addMembersCancel" class="btn btn-sm btn-secondary" onclick="AddNewMembersCancel()">Cancel</a>
        </div>

    </form>
    <script>
        $('.search-box').SumoSelect({ csvDispCount: 3, search: true, searchText: 'Enter here.' });
    </script>
    <script>
        function AddNewMembersCancel() {
            $('#addNewMemberModal').modal('hide');
        }
    </script>

</body>
</html>

I have given validations of selecting at least one member but when I click submit button without selecting member then it redirects to new page and shows the message there. I want to show the message on the same partial view when clicked submit?

You need to add your validation scripts jquery.validate.min.js and jquery.validate.unobtrusive.min.js .

Client-side validation

The partial view _ValidationScriptsPartial.cshtml from shared folder can be added to your view:

<partial name="_ValidationScriptsPartial" />

You have <form> element with a submit button which by default will cause you page to reload on submit .

In order to show the error on the same page when you click submit, you need to prevent the default behavior of the form.

First, you will need some kind of id on your form element. Let's say the id is new-members-form .

<form id="new-members-form" class="console-panel grid-stack-item-content" asp-action="GetNewMembers" asp-controller="Group" method="post">
...
</form>

Then, you need to select the form and tell it to stop executing the default behavior on form submit.

With JQuery:

$("new-members-form").on("submit", (event) => { event.preventDefault(); });

Or plain JS:

document.getElementById("new-members-form").addEventListener("submit", function(event) {
    event.preventDefault();
});

在此处输入图像描述

When first time to view or failed to add, remember to set the memberList .

Codes of controller:

     //Members to SelectListItem
    public IList<SelectListItem> GetMembers()
    {
        var members = new List<Member>
        {
            new Member {Id = Guid.NewGuid(), Name = "Ada"},
            new Member {Id = Guid.NewGuid(), Name = "Brain"},
            new Member {Id = Guid.NewGuid(), Name = "Cater"},
        };

        var memberListItem = members
       .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() })
       .ToList();

        return memberListItem;
    }


    [Route("/members")]
    public IActionResult _GetNewMembers()
    {
        var model = new NewMembersAddViewModel { 
                           membersList = GetMembers() 
                    };

        return View(model);
    }

    
    [Route("/api/Group/GetNewMembers")]
    [HttpPost]
    public IActionResult GetNewMembers(NewMembersAddViewModel groupMemberData)
    {
        if (ModelState.IsValid)
        {
            //Success                
            return RedirectToAction("GroupMembers", "Group", new { groupId = groupMemberData.GroupId });

        }
        else
        {
            //when failed, set the memberList again.
            groupMemberData.membersList = GetMembers(); 

            return PartialView("_GetNewMembers", groupMemberData);
        }

    }

Codes of view are same as you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM