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:
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!
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: