locked
Blazor WASM with CRUD against Web API Endpoint - Insert() does Insert anything in db RRS feed

  • Question

  • User379720387 posted

    Extending the functionality to be able to add items:

    Debugger makes it to ClearFields, but at that time no new record was added.

    Is the highlighted code correct?

    @if (students != null) // Insert form
        {
            <input placeholder="First Name" bind="@firstName" />
            <br />
            <input placeholder="Last Name" bind="@lastName" />
            <br />
            <input placeholder="School" bind="@school" />
            <br />
            <button @onclick="@Insert" class="btn btn-warning">Insert</button>
        }
    
    @functions {
        Student[] students;
    
        string studentId;
        string firstName;
        string lastName;
        string school;
    
    
        protected async override Task OnInitializedAsync()
        {
            try
            {
                var httpClient = ClientFactory.CreateClient("ServerAPI");
                students = await httpClient.GetFromJsonAsync<Student[]>("api/students");
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
    
    
        }
    
        private async Task Insert()
        {
            Student student = new Student()
            {
                StudentId = Guid.NewGuid().ToString(),
                FirstName = firstName,
                LastName = lastName,
                School = school
            };
            try
            {
    
    
                var httpClient = ClientFactory.CreateClient("ServerAPI");
                await httpClient.PostAsJsonAsync("api/students", student);
                ClearFields();
                students = await httpClient.GetFromJsonAsync<Student[]>("api/students");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }



    Thursday, May 28, 2020 7:17 PM

Answers

  • User475983607 posted

    According to the Blazor docs, use an EditForm.

    https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1

    @page "/studentInsert"
    @inject IHttpClientFactory ClientFactory
    
    <h1>Save Student</h1>
    
    <EditForm Model="@Student" OnValidSubmit="HandleValidSubmit">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <div>
            <InputText id="firstname" @bind-Value="Student.FirstName" />
        </div>  
        <div>
            <InputText id="lastname" @bind-Value="Student.LastName" />
        </div>
        <div>
            <InputText id="scool" @bind-Value="Student.School" />
        </div>
    
        <button type="submit">Submit</button>
    </EditForm>
    
    @code {
        Student Student = new Student();
    
        private async Task HandleValidSubmit()
        {
            try
            {
                var httpClient = ClientFactory.CreateClient("ServerAPI");
                await httpClient.PostAsJsonAsync("api/students", Student);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 28, 2020 9:43 PM
  • User475983607 posted

    wavemaster

    I like that approach, but where does this live? Only place I have a .cs is Program.cs

    If so, does it need to be part of Task Main(), and how?

    using System.ComponentModel.DataAnnotations;
    
    public class ExampleModel
    {
        [Required]
        [StringLength(10, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }
    }

    Your solution has a SchoolLibrary project that contains a Student Model.  The SchoolLibrary is shared by the Blazor and API applications.  I would put any new Models in the same library.  

    If you want the class in the Blazor project, then just create a folder (Models) and put the class in the Models folder.  Keep in mind, doing so mean you cannot shared the class with the API.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 29, 2020 12:29 PM
  • User475983607 posted

    @Student is a variable not a class.  Did you define a the variable as Student or maybe with a lower case "s" student.  

    <EditForm Model="@Student" OnValidSubmit="Student">

    Anyway, the code I posted above works.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 29, 2020 2:59 PM

All replies

  • User475983607 posted

    According to the Blazor docs, use an EditForm.

    https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1

    @page "/studentInsert"
    @inject IHttpClientFactory ClientFactory
    
    <h1>Save Student</h1>
    
    <EditForm Model="@Student" OnValidSubmit="HandleValidSubmit">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <div>
            <InputText id="firstname" @bind-Value="Student.FirstName" />
        </div>  
        <div>
            <InputText id="lastname" @bind-Value="Student.LastName" />
        </div>
        <div>
            <InputText id="scool" @bind-Value="Student.School" />
        </div>
    
        <button type="submit">Submit</button>
    </EditForm>
    
    @code {
        Student Student = new Student();
    
        private async Task HandleValidSubmit()
        {
            try
            {
                var httpClient = ClientFactory.CreateClient("ServerAPI");
                await httpClient.PostAsJsonAsync("api/students", Student);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 28, 2020 9:43 PM
  • User379720387 posted

    I like that approach, but where does this live? Only place I have a .cs is Program.cs

    If so, does it need to be part of Task Main(), and how?

    using System.ComponentModel.DataAnnotations;
    
    public class ExampleModel
    {
        [Required]
        [StringLength(10, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }
    }

    Thursday, May 28, 2020 11:18 PM
  • User475983607 posted

    wavemaster

    I like that approach, but where does this live? Only place I have a .cs is Program.cs

    If so, does it need to be part of Task Main(), and how?

    using System.ComponentModel.DataAnnotations;
    
    public class ExampleModel
    {
        [Required]
        [StringLength(10, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }
    }

    Your solution has a SchoolLibrary project that contains a Student Model.  The SchoolLibrary is shared by the Blazor and API applications.  I would put any new Models in the same library.  

    If you want the class in the Blazor project, then just create a folder (Models) and put the class in the Models folder.  Keep in mind, doing so mean you cannot shared the class with the API.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 29, 2020 12:29 PM
  • User379720387 posted

    This is what SchoolLibrary looks like:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Text;
    
    namespace SchoolLibrary
    {
        public class Student
        {
            public string StudentId { get; set; }
            [Required]
            public string FirstName { get; set; }
            [Required]
            public string LastName { get; set; }
            [Required]
            public string School { get; set; }
        }

    I don't think that I could do this:

    <EditForm Model="@Student" OnValidSubmit="Student">

    @Student has a squiggle for Student is a type which is not valid in the given context.

    Friday, May 29, 2020 1:55 PM
  • User475983607 posted

    @Student is a variable not a class.  Did you define a the variable as Student or maybe with a lower case "s" student.  

    <EditForm Model="@Student" OnValidSubmit="Student">

    Anyway, the code I posted above works.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 29, 2020 2:59 PM
  • User379720387 posted

    Yup, got it working here too!

    Thanks.

    Friday, May 29, 2020 7:32 PM