Почему мой Inventory.cshtml ничего не получает и не отправляет от контроллеров или моделей. в ASP.NET Core MVCC#

Место общения программистов C#
Ответить
Anonymous
 Почему мой Inventory.cshtml ничего не получает и не отправляет от контроллеров или моделей. в ASP.NET Core MVC

Сообщение Anonymous »

Я пытаюсь исправить все опечатки во всем пространстве имен, из-за которых могла возникнуть ошибка. Но на данный момент я не получаю никаких ошибок от консоли или терминала, поэтому не могу найти проблему. Проблема в том, что я пытаюсь получить ошибки или сообщения от моделей и контроллеров в моем Inventory.cshtml.
Вот мой код для первого Product.cs в сущностях:

Код: Выделить всё

using System.ComponentModel.DataAnnotations;

namespace SportsCapstone.Entities
{
public class Product
{
[Key]
public int Id { get; set; }

// public byte[] Image { get; set; } // Storing image as byte array

[Required(ErrorMessage = "Product is required.")]
[MaxLength(20, ErrorMessage = "Max 20 characters allowed")]
public string ProductName { get; set; }

[Required(ErrorMessage = "Brand is required.")]
[MaxLength(20, ErrorMessage = "Max 20 characters allowed")]
public string ProductBrand { get; set; }

[Required(ErrorMessage = "Quantity should not be empty")]
[Range(1, int.MaxValue, ErrorMessage = "Quantity Must be atleast 1.")]
public int Quantity { get; set; }

[Required(ErrorMessage = "Type of Product is required.")]
[MaxLength(20, ErrorMessage = "Max 20 characters allowed")]
public string TypeOfProduct { get; set; }

[Required(ErrorMessage = "Type of Age is required.")]
[Range(1, 60, ErrorMessage = "Age should not be more than 60")]
public string AgeRange { get; set; }
}
}
А это мой AppDbContext.cs:

Код: Выделить всё

using Microsoft.EntityFrameworkCore;

namespace SportsCapstone.Entities
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options)
: base(options) { }
...
public DbSet
 Products { get; set; } // Add this line

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
....
// Configure the Product entity
modelBuilder.Entity()
.Property(p => p.ProductName)
.IsRequired();

modelBuilder.Entity()
.Property(p => p.ProductBrand)
.IsRequired(); // Example for Brand

modelBuilder.Entity()
.Property(p => p.Quantity)
.IsRequired(); // Example for Quantity

modelBuilder.Entity()
.Property(p => p.TypeOfProduct)
.IsRequired(); // Example for Quantity
modelBuilder.Entity()
.Property(p => p.AgeRange)
.IsRequired(); // Example for Quantity

// modelBuilder.Entity()
//         .Property(p => p.Image)
//         .IsRequired(); // Add this line if you want to ensure the Image property is required

// Continue adding other configurations as necessary...

base.OnModelCreating(modelBuilder);
}

}
}
Это мой InventoryController:

Код: Выделить всё

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SportsCapstone.Models; // This should be your models namespace
using SportsCapstone.Entities; // Keep if you need to reference Product

namespace SportsCapstone.Controllers // Corrected namespace
{
[Authorize]
public class InventoryController : Controller
{
private readonly AppDbContext _dbContext;

public InventoryController(AppDbContext appDbContext)
{
_dbContext = appDbContext;
}

public IActionResult Create()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create(InventoryItem model) // Change to InventoryItem
{
if (ModelState.IsValid)
{
// If needed, convert InventoryItem to Product here
var product = new Product
{
ProductName = model.ProductName,
ProductBrand = model.ProductBrand,
Quantity = model.Quantity,
TypeOfProduct = model.TypeOfProduct,
AgeRange = model.AgeRange
};

await _dbContext.Products.AddAsync(product);
await _dbContext.SaveChangesAsync();

ViewBag.Message = "Product created successfully!";
return RedirectToAction("Index"); // Adjust as needed
}

return View(model); // Return the view with validation errors
}
}
}
И, наконец, мой InventoryItem:

Код: Выделить всё

using System.ComponentModel.DataAnnotations;

namespace SportsCapstone.Models
{
public class InventoryItem
{
[Required(ErrorMessage = "Product name is required.")]
[MaxLength(20, ErrorMessage = "Max 20 characters allowed.")]
public string ProductName { get; set; }

[Required(ErrorMessage = "Product brand is required.")]
[MaxLength(20, ErrorMessage = "Max 20 characters allowed.")]
public string ProductBrand { get; set; }

[Required(ErrorMessage = "Quantity is required.")]
[Range(1, int.MaxValue, ErrorMessage = "Quantity must be a positive number.")]
public int Quantity { get; set; } // Changed to int

[Required(ErrorMessage = "Type of product is required.")]
[MaxLength(20, ErrorMessage = "Max 20 characters allowed.")]
public string TypeOfProduct { get; set; }

[Required(ErrorMessage = "Age range is required.")]
[Range(5, 20, ErrorMessage = "Age range must be between 5 and 20.")]
public string AgeRange { get; set; }

// [Required(ErrorMessage = "Image is required.")]
// public IFormFile Image { get; set;  } // For file uploads
}
}
Теперь я пытаюсь создать функцию создания в Views/Dasboard/Inventory.cshtml

Код: Выделить всё

            @if (@ViewBag.Message != null)
{

@ViewBag.Message

}








@*  *@

@*  *@

@*  *@












 Type of Product 
 Cloth 
 Pants 
 Accessories 
 Sports Gear 





 Age 
 -18 
 18+ 





  Create Item 



но я ничего не получаю и не отправляю в контроллерах или моделях... Может ли кто-нибудь сказать мне, что дело в именах файлов, пространстве имен или в чем-то еще? Я не могу найти проблему, поскольку не получаю никаких ошибок или сообщений в Inventory.cshtml

Подробнее здесь: https://stackoverflow.com/questions/790 ... trollers-o
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»