How to apply data notation for mandatory add Server name new row when insert ?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-02-15T07:15:16.6033333+00:00

I working on blazor app i face issue I can't apply validation to fieldname

SeverName using data notation when make insert to new row server name .

I need to validate server name field to become not empty and required

if server name is empty then message display for user Server name is required .

so server name must be mandatory .

so my code as below :

1- model servername

  public class ServerNames
    {
        [Key]
        public int ServerID { get; set; }
        public string Server_Name{ get; set; }

    }
2-create action controller

[HttpPost]
        public ActionResult AddServer(ServerNames ServersName)
        {
            return Ok(_IserverNamesService.Insert(ServersName));
        }
3- blazor.razor component

@page "/Servers/ServersNames"

<h1>Server Name</h1>

<button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal" @onclick="AddClick">
    Add ServerNames

</button>
<table class="class table-striped">
    <thead>
        <tr>
            <th>ServerId</th>
            <th>Server Name</th>

        </tr>
    </thead>
    <tbody>
        @foreach (var serv in ServerName)
        {
        <tr>
            <td>@serv.serverID</td>
            <td>@serv.server_Name</td>
            
        </tr>
        }
    </tbody>

</table>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">
                    @ModalTitle
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </h5>
            </div>
            <div class="modal-body">
                <div class="d-flex flex-row bd-highlight mb-3">
                    <div class="p-2 w-100 bd-highlight">
                        <div class="form-group row">
                    <label for="example-text-input" class="col-3 col-form-label">Server Name</label>
                            <div class="col-9">
                    <input type="text" class="form-control" @bind="server_Name" />
                    </div>
                    </div>
                         @if (ModalTitle == "Add Server")
                {
                    <button type="button" class="btn btn-primary" @onclick="CreateClick">
                        Create
                    </button>
                }
                      
                    
                    </div>
                </div>

            </div>

        </div>

    </div>

</div>


@code
{
    public class ServerNamesClass
    {
        public int serverID { get; set; }
        public string server_Name { get; set; }
    }
 


    private string ModalTitle;
    private int serverID;
    private string server_Name;


    

    
   // for insert 
    private async Task CreateClick()
    {
        var deptobj = new ServerNamesClass() { server_Name = server_Name};
        var request = new HttpRequestMessage(HttpMethod.Post, config["API_URL"] + "ServerNames");
        request.Content = new StringContent(JsonSerializer.Serialize(deptobj), null, "application/json");
        var client = ClientFactory.CreateClient();
        var response = await client.SendAsync(request);
     
        string res = await response.Content.ReadAsStringAsync();
        await JS.InvokeVoidAsync("alert", "Success Inserted");
  


    }
   
    
    private async void AddClick()
    {
        ModalTitle = "Add Server";
        serverID = 0;
        server_Name = "";
       
        


    }

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,553 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,578 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,326 Reputation points Microsoft Vendor
    2023-02-16T06:16:02.4033333+00:00

    Hi @Ahmed Salah Abed Elaziz

    In Blazor application, you can use the EditForm component and DataAnnotationsValidator component to work with the data annotations validation.

    Refer to the following sample:

    @page "/addserver" 
    @using System.ComponentModel.DataAnnotations;
    <h1>Server Name</h1>
    
    <button type="button" class="btn btn-primary m-2 float-end" data-bs-toggle="modal" data-bs-target="#exampleModal" @onclick="AddClick">
        Add ServerNames 
    </button>
    <table class="class table-striped">
        <thead>
            <tr>
                <th>ServerId</th>
                <th>Server Name</th>
    
            </tr>
        </thead>
        <tbody>
            @foreach (var serv in ServerName)
            {
            <tr>
                <td>@serv.serverID</td>
                <td>@serv.server_Name</td>
                
            </tr>
            }
        </tbody>
    
    </table>
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">
                        @ModalTitle
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </h5>
                </div>
                <div class="modal-body">
                    <div class="d-flex flex-row bd-highlight mb-3">
                        <div class="p-2 w-100 bd-highlight">
    
                            <EditForm EditContext="@createContext" OnSubmit="CreateClick">
                                <DataAnnotationsValidator />
                                <div class="form-group row">
                                    <label for="example-text-input" class="col-3 col-form-label">Server Name</label>
                                    <div class="col-9">
                                        <InputText id="server_Name" @bind-Value="newserver.server_Name" />
                                    </div>
                                    <div class="col-3"><ValidationMessage For="@(() => newserver.server_Name)" /> </div>
                                </div>
                                @if (ModalTitle == "Add Server")
                                {
                                    <button type="submit" class="btn btn-primary" >
                                        Create
                                    </button>
                                }
                            </EditForm>
    
                        </div>
                    </div> 
                </div> 
            </div> 
        </div> 
    </div> 
    @code
    {
        public class ServerNamesClass
        {
            public int serverID { get; set; }
            [Required]
            public string server_Name { get; set; }
        } 
        private string ModalTitle; 
    
        ServerNamesClass newserver = new ServerNamesClass();
        private List<ServerNamesClass> ServerName { get; set; }
    
        private EditContext? createContext;
    
        protected override void OnInitialized()
        {
            createContext = new(newserver);
            ServerName = new List<ServerNamesClass>();
        }
        // for insert HandleValidSubmit
        private async Task CreateClick()
        {
            if (createContext != null && createContext.Validate())
            {
                //the form is valid
                var item = new ServerNamesClass()
                    {
                        serverID = ServerName.Count + 1,
                        server_Name = newserver.server_Name
                    }; 
                ServerName.Add(item);
    
                await Task.CompletedTask;
            }
            else
            {
                //Form is INVALID
            } 
        } 
        private async void AddClick()
        {
            ModalTitle = "Add Server";
            newserver.serverID = 0;
            newserver.server_Name = "";
        }
    }
    
    

    The output as below:

    image2

    More detail information about validation in Blazor, see ASP.NET Core Blazor forms and input components.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.