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

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

Сообщение Anonymous »

Я пытаюсь исправить все опечатки во всем пространстве имен, из-за которых могла возникнуть ошибка. Но на данный момент я не получаю никаких ошибок от консоли или терминала, поэтому не могу найти проблему. Проблема в том, что я пытаюсь получить ошибки или сообщения от моделей и контроллеров в моем Inventory.cshtml.
Обратите внимание, что у меня разные макеты (я не знаю). если на это влияют макеты).
Как для _DashboardLayout и _Layout в общей папке.
Вот путь к папке/файлу пути, которые у меня есть, чтобы они могли лучше понять. MVC1 MVC2
поэтому у меня есть сущности для 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; }
}
}

А это InventoryItem.cs
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
}
}


А это 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
using Microsoft.EntityFrameworkCore;

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

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

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

try
{
_dbContext.Products.Add(product);
_dbContext.SaveChanges();
ModelState.Clear();
ViewBag.Message = $"{product.ProductName} registered successfully. Please Login.";
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Please enter a unique Email or Password.");
return View(model);
}
return View();
}
return View("Inventory", model); //return model with correct view name
}
}
}


затем обновляется Inventory.cshtml. Входные данные AgeRange представляют собой не целое число, а строку, потому что я верну его взрослым или детям@model SportsCapstone.Models.InventoryItem
@{
Layout = "_DashboardLayout";
}

...

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

@ViewBag.Message

}








@* *@

@* *@

@* *@












Type of Product
Cloth
Pants
Accessories
Sports Gear





Age
-18
18+





Create Item






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

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

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

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

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

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