How do I insert input from form to database?

My model looks like this:

public class Customer
{
    public int CustomerId { get; set; }

    [Required(ErrorMessage = "Please enter a valid first name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter a valid last name")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please enter a valid address")]
    public string Address { get; set; }

    public string Email { get; set; }

    [Required(ErrorMessage = "Please enter a valid city")]
    public string City { get; set; }

    public string Phone { get; set; }

    [Range(1, 5, ErrorMessage = "Please enter a valid country")]
    public int CountryId { get; set; }

    public Country Country { get; set; }

    [Required(ErrorMessage = "Please enter a valid state")]
    public string State { get; set; }

    [Required(ErrorMessage = "Please enter a valid postal code")]
    public string PostalCode { get; set; }

    public string fullname => FirstName + LastName;
}

My controller looks like this:

public class CustomerController : Controller
{
    private CustomerContext context { get; set; }

    public CustomerController(CustomerContext ctx)
    {
        context = ctx;
    }

    public IActionResult List()
    {
        var customers = context.Customers.ToList();
        return View(customers);
    }

    [HttpGet]
    public IActionResult Add()
    {
        ViewBag.Action = "Add";
        ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList();
        return View("Edit", new Customer());
    }

    [HttpGet]
    public IActionResult Edit(int id)
    {
        ViewBag.Action = "Edit";
        ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList();

        var customer = context.Customers
            .Include(c => c.Country)
            .FirstOrDefault(c => c.CustomerId == id);

        return View(customer);
    }

    [HttpPost]
    public IActionResult Edit(Customer customer)
    {
        string action = (customer.CustomerId == 0) ? "Add" : "Edit";

        if (ModelState.IsValid)
        {
            if (action == "Add")
            {
                context.Customers.Add(customer);
            }
            else
            {
                context.Customers.Update(customer);

            }
            context.SaveChanges();
            return RedirectToAction("List", "Customer");
        }
        else
        {
            ViewBag.Action = action;
            ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList();
            return View(customer);
        }
    }

I also have a DbContext file with data i created to test other things:

public class CustomerContext : DbContext
{
    public CustomerContext(DbContextOptions<CustomerContext> options)
        :base(options)
    { }

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Country> Countries { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Country>().HasData(
            new Country { CountryId = 1, Name = "Canada"},
            new Country { CountryId = 2, Name = "United States"},
            new Country { CountryId = 3, Name = "United Kingdom" },
            new Country { CountryId = 4, Name = "Mexico" },
            new Country { CountryId = 5, Name = "Russia" }
            );

        modelBuilder.Entity<Customer>().HasData(
            new Customer
            {
                CustomerId = 1,
                FirstName = "Bruce",
                LastName = "Wayne",
                Phone = "416-123-4567",
                Email = "bruce.wayne@gmail.com",
                CountryId = 1,
                Address = "123 sesame street",
                City = "Toronto",
                PostalCode = "L812A",
                State = "Ontario"
            }
            );
    }

I already did the add-migration and updated my database via the package manager console. I created a form in the view that looks like this:

<form method="post" asp-action="Add">
<div asp-validation-summary="All">

    <div>
        <label asp-for="FirstName">First Name</label>
        <input type="text" name="FirstName" asp-for="FirstName" />
    </div>

    <div>
        <label asp-for="LastName">Last Name</label>
        <input type="text" name="LastName" asp-for="LastName" />
    </div>

    <div>
        <label asp-for="Address">Address</label>
        <input type="text" name="Address" asp-for="Address" />
    </div>

    <div>
        <label asp-for="City">City</label>
        <input type="text" name="City" asp-for="City" />
    </div>

    <div>
        <label asp-for="State">State</label>
        <input type="text" name="State" asp-for="State" />
    </div>

    <div>
        <label asp-for="PostalCode">Postal Code</label>
        <input type="text" name="Postal Code" asp-for="PostalCode" />
    </div>

    <div>
        <label asp-for="CountryId">Country</label>
        <select name="Country" asp-for="CountryId">
            @foreach (Country country in ViewBag.Countries)
            {
                <option value="@country.CountryId">@country.Name</option>
            }
        </select>
    </div>

    <div>
        <label asp-for="Email">Email</label>
        <input type="text" name="Email" asp-for="Email" />
    </div>

    <div>
        <label asp-for="Phone">Phone</label>
        <input type="text" name="Phone" asp-for="Phone" />
    </div>

    <input type="hidden" asp-for="CustomerId" />
</div>

<button type="submit" value="Save" asp-controller="Customer" asp-action="List">Save</button>
Cancel

I've tried looking up multiple different solutions to solve my issue but I cant seem to figure out how to solve it. If someone could help me that would be much appreciated. thanks in advance.

1 answer

  • answered 2021-02-27 05:27 Mukarram Javid

    You are call wrong actionName in View

    asp-action="Add"
    

    But if you will see in your Controller action your logic is implemented in Edit controller So, you change yoir Razor View form It will look like this

    <form method="post" asp-action="Edit" >