ASP.NET MVC application : form redirects to non-existing page instead of saving data to database

I am working on an ASP.NET MVC application where I have created a product page with all the necessary MVC components (model, view, controller). However, when a user fills out the form on the product page and submits it, the application does not save the new product to the database. Instead, it redirects to a non-existing page.

What I’m trying to achieve

On the product page, users can fill out a form to create a new product. The goal is to save the product details to the database when the form is submitted.

What actually happens

Instead of saving the new product to the database, the application redirects to a non-existent page after the form is submitted.

Expected Behavior

When the form is submitted, the new product should be saved to the database, and the user should be redirected to a confirmation page or a list of products.

What I have tried:

  • I checked the routing configuration in program.cs and confirmed that the routes should map correctly.
  • I verified that the form method is set to POST.
  • I validated the model and ensured it is correct.

Model class:

namespace My_Name_Space.Models
{
    public class Product
    {
        [Required]
        [Key]
        public  int Id { get; set; }
        
        [Required]
        public  string Name { get; set; }
        
        [Required]
        public  string Description { get; set; }

        [Required]
        [Range(0, double.MaxValue, ErrorMessage = "Price must be a positive number.")]
        public  string Price { get; set; }

        [Required]
        public  string ImageUrl { get; set; }

        [Required]
        [Range(0, int.MaxValue, ErrorMessage = "Stock must be a non-negative integer.")]
        public int Stock { get; set; }
    }
}

Controller:

public async Task<IActionResult> ManageProducts()
{
    var products = await _context.Products.ToListAsync();
    return View(products);
}

/* Manage Product Create GET*/
public IActionResult CreateProducts()
{
    return View();
}
 
/*  add actions to create, edit, and delete products*/
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateProducts(Product product)
{
    if (ModelState.IsValid)
    {
          _context.Add(product);
          await _context.SaveChangesAsync();
          return RedirectToAction(nameof(ManageProducts));
    }
    else
    {
          // Inspect the ModelState to understand why it's not valid //
          var errors = ModelState.Values.SelectMany(v => v.Errors);
    }

    return View(product);
}

View:

<form asp-action="CreateProduct" asp-controller="Admin" method="post">
    <div class="form-group">
        <label asp-for="Name" class="control-label"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Description" class="control-label"></label>
        <textarea asp-for="Description" class="form-control"></textarea>
        <span asp-validation-for="Description" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Price" class="control-label"></label>
        <input asp-for="Price" class="form-control" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Stock" class="control-label"></label>
        <input asp-for="Stock" class="form-control" />
        <span asp-validation-for="Stock" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="ImageUrl" class="control-label"></label>
        <input asp-for="ImageUrl" class="form-control" />
        <span asp-validation-for="ImageUrl" class="text-danger"></span>
    </div>

    <div class="form-group">
        <button type="submit" value="Create" class="btn btn-primary">Create</button>
       
    </div>
</form>
<script>

    <script src="~/js/create-product.js"></script>
</script>

site.js script:

document.addEventListener("DOMContentLoaded", function () {
    // Image URL preview functionality
    const imageUrlInput = document.querySelector('input[name="ImageUrl"]');
    const imagePreview = document.createElement('img');
    imagePreview.id = 'imagePreview';
    imageUrlInput.parentNode.appendChild(imagePreview);

    imageUrlInput.addEventListener("input", function () {
        const url = imageUrlInput.value;
        if (url) {
            imagePreview.src = url;
            imagePreview.style.display = 'block';
        } else {
            imagePreview.style.display = 'none';
        }
    });
});

Map controllers in Program.cs:

//other essential services

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name:"admin",
    pattern: "{controller=Admin}/{action=ManageProducts}/{id?}");

app.MapControllerRoute(
    name: "login",
    pattern: "Login",
    defaults: new { controller = "Login", action = "Index" });

File structure:

ProjectName/
     │
     ├── Controllers/
     │   └── ProductController.cs
     │
     ├── Models/
     │   └── Product.cs
     │
     ├── Views/
     │   └── Admin/
     │       ├── CreateProduct.cshtml
     │       └── Index.cshtml
     │
     ├── wwwroot/
     |   ├── css/
     |   |     └── site.css
     │   └── js/
     |       └── create-product.js
     │
     │
     ├── appsettings.json
     └── program.cs

Every help is deeply appreciated, excuse my noob code and please address me if I’ve doing something wrong!

3

According to the code you provided and the relevant project structure, your Expected Behavior can be implemented through Admincontroller.

the application does not save the new product to the database.
Instead, it redirects to a non-existing page.

The reason for the problem is that in your form, the corresponding method submitted is Admincontroller/CreateProduct, but in your project structure, the controller name defined in your Controllers is Productcontroller, so the method cannot be correctly matched after the form is submitted. You can change Productcontroller to Admincontroller.

Secondly, in the controller method, the default behavior of the View method return View(); is to return a view with the same name as the action method from which it is called, so the method name needs to correspond to the view name.

For example: if the method name in the controller is CreateProducts, then the corresponding view name should also be CreateProducts instead of CreateProduct. And the method corresponding to the form submission should be Admincontroller/CreateProducts instead of Admincontroller/CreateProduct. Otherwise, the route will not be correctly matched to the method.

And in your routing configuration, only the default operation method is configured for the controller, which is ManageProducts. If you have more custom routing configurations, you can refer to this document for configuration:https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-8.0.

the user should be redirected to a confirmation page or a list of
products.

If you want to redirect to a separate page like ManageProducts, then you need to create a corresponding page ManageProducts in the Views/Admin folder. Here is a complete example for your reference:

Controller:

 public class AdminController : Controller
 {
     private readonly ApplicationDbContext _dbContext;
     public AdminController(ILogger<HomeController> logger, ApplicationDbContext dbContext)
     {
         
         _dbContext = dbContext;
     }

     public IActionResult Index()
     {
         return View();
     }
     public async Task<IActionResult> ManageProducts()
     {
         var products = await _dbContext.Products.ToListAsync();
         return View(products);
     }

     /* Manage Product Create GET*/
     public IActionResult CreateProducts()
     {
         return View();
     }

     /*  add actions to create, edit, and delete products*/
     [HttpPost]
     [ValidateAntiForgeryToken]
     public async Task<IActionResult> CreateProducts(Product product)
     {
         if (ModelState.IsValid)
         {
             _dbContext.Products.Add(product);
             await _dbContext.SaveChangesAsync();
             return RedirectToAction("ManageProducts");
         }

         return View(product);
     }
 }

Views/Admin/CreateProducts:

@model Product

<form asp-action="CreateProducts" asp-controller="Admin" method="post">
    <div class="form-group">
        <label asp-for="Name" class="control-label"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Description" class="control-label"></label>
        <textarea asp-for="Description" class="form-control"></textarea>
        <span asp-validation-for="Description" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Price" class="control-label"></label>
        <input asp-for="Price" class="form-control" />
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Stock" class="control-label"></label>
        <input asp-for="Stock" class="form-control" />
        <span asp-validation-for="Stock" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="ImageUrl" class="control-label"></label>
        <input asp-for="ImageUrl" class="form-control" />
        <span asp-validation-for="ImageUrl" class="text-danger"></span>
    </div>

    <div class="form-group">
        <button type="submit" value="Create" class="btn btn-primary">Create</button>

    </div>
</form>

Views/Admin/ManageProducts:

@model IEnumerable<Product>

@{
    ViewData["Title"] = "Manage Products";
}

<h2>Manage Products</h2>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th>Stock</th>
            <th>Image</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Name</td>
                <td>@product.Description</td>
                <td>@product.Price</td>
                <td>@product.Stock</td>
                <td>
                    <img src="@product.ImageUrl" alt="@product.Name" style="width: 100px; height: auto;" />
                </td>
                <td>
                    <a asp-action="EditProduct" asp-route-id="@product.Id" class="btn btn-warning">Edit</a>
                    <a asp-action="DeleteProduct" asp-route-id="@product.Id" class="btn btn-danger">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

When I submit the relevant information:

We can see that we can redirect to the list page normally and save successfully:

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật