Search code examples
asp.net-mvcentity-frameworkasp.net-corerazor-pagesasp.net-mvc-scaffolding

Scaffolded Razor Create Page doesn't add item


I created a "create" razor page through scaffolding for the following model:

public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProdId { get; set; }
    [Required]
    public string ProdName { get; set; }
    [Required]  
    public float Price { get; set; }

    [Required]
    [ForeignKey("Category")]
    public int CategoryID { get; set; }

    [Required]
    [ForeignKey("Supplier")]
    public int SupplierID { get; set; }

    
    public virtual Category category { get; set; }
    
    public virtual Supplier supplier { get; set; }


    public List<Review> reviews { get; set; }

    public List<ShoppingCart> shoppingCarts { get; set; }

    public List<Order> orders { get; set; }

}

The following razor page was created:

@page
@model WebStore.Pages.Products.CreateModel
@using Microsoft.AspNetCore.Mvc.ViewEngines
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Create</h1>

<h4>Product</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Product.ProdName" class="control-label"></label>
                <input asp-for="Product.ProdName" class="form-control" />
                <span asp-validation-for="Product.ProdName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.Price" class="control-label"></label>
                <input asp-for="Product.Price" class="form-control" />
                <span asp-validation-for="Product.Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.CategoryID" class="control-label"></label>
                <select asp-for="Product.CategoryID" class ="form-control" asp-items="ViewBag.CategoryID"></select>
            </div>
            <div class="form-group">
                <label asp-for="Product.SupplierID" class="control-label"></label>
                <select asp-for="Product.SupplierID" class ="form-control" asp-items="ViewBag.SupplierID"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

with the following create.cs related file:

public class CreateModel : PageModel
{
    private readonly WebStore.MyDbContext _context;

    public CreateModel(WebStore.MyDbContext context)
    {
        _context = context;
    }

    public IActionResult OnGet()
    {
    ViewData["CategoryID"] = new SelectList(_context.Categories, "CatId", "CatDescription");
    ViewData["SupplierID"] = new SelectList(_context.Suppliers, "supplierId", "supplierId");
        return Page();
    }

    [BindProperty]
    public Product Product { get; set; } = default!;
    

    // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
    public async Task<IActionResult> OnPostAsync()
    {
      if (!ModelState.IsValid || _context.Products == null || Product == null)
        {
            return Page();
        }

        _context.Products.Add(Product);
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

The problem I face is that when i try to add another item and click Create, no item is actually added and nothing changes in the database nor do I get redirected to index.

Create Page

the CategoryID and supplierID are in refrence to other entities.


Solution

  • Can you debug the page? I believe that either your _context (did you register your DbContext) or your Product is null or the ModelState is not valid. In that case the Page is just returned before saving the product in the database.

    Set a breakpoint on your call to SaveChangesAsync(); Depending on your database you might also use a profiler to see whether the database is called or you could setup a logger for your SQL statments.