asp.net 模型不能进入如果(ModelState.IsValid)

ztmd8pv5  于 2022-11-26  发布在  .NET
关注(0)|答案(1)|浏览(96)

这是我的控制器代码,一开始我被卡住了,因为数据没有进入数据库,VS没有显示任何错误。但是现在我在if条件(Upsert POST方法)中设置了一个断点,“Watch 1”显示了一些奇怪的东西,比如“Model.Product.Id error CS 0103:名称“Model”在当前上下文中不存在”和“$exception error CS 0103:名称“$exception”在当前上下文””中不存在.

namespace KeramoShop.Controllers
{
    public class ProductController : Controller

    {
        private readonly ApplicationDbContext _db;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public ProductController(ApplicationDbContext db, IWebHostEnvironment webHostEnvironment)
        {
            _db = db;
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Index()
        {
            IEnumerable<Product> objList = _db.Product;
            foreach (var obj in objList)
            {
                obj.Category = _db.Category.FirstOrDefault(u => u.Id == obj.CategoryId);
            }
            return View(objList);
        }

        /// <summary>
        /// GET method for CREATE
        /// </summary>
        /// <returns></returns>
        public IActionResult Upsert(int? id)
        {
            //IEnumerable<SelectListItem> CategoryDropDown = _db.Category.Select(i=> new SelectListItem { 
            //Text = i.Name,
            //Value = i.Id.ToString()
            //});

            //ViewBag.CategoryDropDown = CategoryDropDown;

            //Product product = new Product();

            ProductVM productVM = new ProductVM()
            {
                Product = new Product(),
                CategorySelectList = _db.Category.Select(i => new SelectListItem
                {
                    Text = i.Name,
                    Value = i.Id.ToString()
                })
            };

            if (id == null)
            {
                return View(productVM); //Для создания
            }
            else
            {
                productVM.Product = _db.Product.Find(id);
                if (productVM.Product == null)
                {
                    return NotFound();
                }
                return View(productVM);
            }
        }
        /// <summary>
        /// POST method for CREATE
        /// </summary>
        /// <returns></returns>

        [HttpPost]
        [ValidateAntiForgeryToken] //-Токен защиты от взлома
        public IActionResult Upsert(ProductVM productVM)
        {
            if (ModelState.IsValid)
            {

                var files = HttpContext.Request.Form.Files;
                string webRootPath = _webHostEnvironment.WebRootPath;

                if (productVM.Product.Id == 0)
                {
                    string upload = webRootPath + WC.ImagePath;// Создание
                    string fileName = Guid.NewGuid().ToString();
                    string extention = Path.GetExtension(files[0].FileName);

                    //var oldFile = Path.GetCombine (upload, objFromDb.Image)

                    using (var fileStream = new FileStream(Path.Combine(upload, fileName + extention), FileMode.Create))
                    {
                        files[0].CopyTo(fileStream);
                    }

                    productVM.Product.Image = fileName + extention;
                    _db.Product.Add(productVM.Product);
                }
                else
                {
                    var objFromDb = _db.Product.AsNoTracking().FirstOrDefault(u => u.Id == productVM.Product.Id);
                    //обновление
                    if (files.Count > 0)
                    {
                        string upload = webRootPath + WC.ImagePath;// Создание
                        string fileName = Guid.NewGuid().ToString();
                        string extention = Path.GetExtension(files[0].FileName);

                        var oldFile = Path.Combine(upload, objFromDb.Image);

                        if (System.IO.File.Exists(oldFile))
                        {
                            System.IO.File.Delete(oldFile);
                        }

                        using (var fileStream = new FileStream(Path.Combine(upload, fileName + extention), FileMode.Create))
                        {
                            files[0].CopyTo(fileStream);
                        }
                        productVM.Product.Image = fileName + extention;
                    }
                    else
                    {
                        productVM.Product.Image = objFromDb.Image;
                    }
                }

                _db.Product.Update(productVM.Product);

                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            else return View(productVM);
        }

        /// <summary>
        /// Get for Delete
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Delete(int? id)
        {
            if (id == null || id == 0)
            {
                return NotFound();
            }

            var obj = _db.Product.Find(id);

            if (obj == null)
            {
                return NotFound();
            }

            return View(obj);
        }

        /// <summary>
        /// POST for Delete
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken] //-Токен защиты от взлома
        public IActionResult DeletePost(int id)
        {

            var obj = _db.Product.Find(id);
            if (obj == null)
            {
                return NotFound();
            }
            _db.Product.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");

        }
    }
}

我的产品型号

namespace KeramoShop.Models
{
    public class Product
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Имя не может быть пустым")]
        [Display(Name = "Название")]
        public string Name { get; set; }

        [Display(Name = "Описание")]
        public string? Description { get; set; }

        [Required(ErrorMessage = "Цена не может быть пустой")]
        [Display(Name = "Цена")]
        [Range(1, int.MaxValue, ErrorMessage = "Цена должна быть больше нуля")]
 
        public double Price { get; set; }

        [Display(Name = "Фотография")]
        public string? Image { get; set; }

        [Display(Name="Тип категории")]

        public int CategoryId { get; set; }

        [ForeignKey("CategoryId")]
        public virtual Category Category { get; set; }
    }
}

我的产品VS模型

namespace KeramoShop.Models.ViewModels
{
    public class ProductVM
    {
        public Product Product { get; set; }
        public  IEnumerable<SelectListItem> CategorySelectList { get; set; }
    }
}

更新插入的我的视图

@model KeramoShop.Models.ViewModels.ProductVM

@{
    var title = "Создать продукт";
}

<form method ="post" enctype="multipart/form-data">
   @if (Model.Product.Id !=0)
   {
     title = "Редактировать продукт";   
   <input asp-for="Product.Id" hidden />
   }
    <div class= "border p-3">
        <div class="form-group row">
            <h2 class="text-info pb-4">@title</h2>
        </div>
            <div class="row">
                <div class="col-8">

                    <div class="form-group row">
                        <div class="col-4 pb-4">
                           <label asp-for="Product.Name"></label>
                        </div>
                        <div class="col-8">
                            <input asp-for="Product.Name" class="form-control" />
                            <span asp-validation-for="Product.Name" class="text-danger"></span>
                        </div>

                    </div>

                    <div class="form-group row">
                        <div class="col-4 pb-4">
                            <label asp-for="Product.Price"></label>

                        </div>
                        <div class="col-8">
                            <input asp-for="Product.Price" class="form-control" />
                             <span asp-validation-for="Product.Price" class="text-danger"></span>
                        </div>
                     </div>

                        
                    <div class="form-group row">
                        <div class="col-4 pb-4">
                            <label asp-for="Product.Description"></label>

                        </div>
                        <div class="col-8">
                            <textarea asp-for="Product.Description" class="form-control summernote"></textarea>
                        </div>
                    </div>

                     <div class="form-group row">
                        <div class="col-4 pb-4">
                            <label asp-for="Product.Image"></label>

                        </div>
                        <div class="col-8">
                            <input type="file" name="files" id="uploadBox" multiple class="form-control" />
                             
                        </div>
                    </div>

                     <div class="form-group row">
                        <div class="col-4 pb-4">
                            <label asp-for="Product.CategoryId"></label>

                        </div>
                        <div class="col-8">

                            <select asp-for="Product.CategoryId" asp-items="@Model.CategorySelectList" class="form-control">
                                <option disabled selected>--Выбeрите категорию-- </option>
                            </select>
                            <span asp-validation-for="Product.CategoryId" class="text-danger"></span>
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-8 offset-4 row p-3">

                            <div class="col">
                                    @if (Model.Product.Id != 0)
                                    {   //изменить
                                        <input type="submit" class="btn btn-info w-100" value="Обновить"/>
                                    }
                                    else
                                    {    //создать
                                         <input type="submit" onclick="return validateInput()" class="btn btn-info w-100" value="Создать"/>
                                    }
                                </div>
                            <div class="col">
                                   <a asp-action = "Index" class="btn btn-success w-100"> Отмена </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-4">
                    @* Keep this empty *@
                </div>
            </div>
    </div>
    

</form>

@section Scripts 
{
    @{ <partial name = "_ValidationScriptsPartial" />}
    <script>
        $(document).ready(function() {
        $('.summernote').summernote({height:250});
        });
        function validateInput() {
            if (document.getElementById("uploadBox").value == "") {
                Swal.fire(
                    'Ошибка!',
                    'Пожалуйста, загрузите картинку!',
                    'error')
                return false;
            }
            else return true;   
        }
    </script>
}

我是新来的asp.net和编程本身,所以我不知道我做错了什么。我希望有人能帮助我!

vkc1a9a2

vkc1a9a21#

但“图像”仍然是空的,如果我试图上传它。
您需要保持名称与您的Image相同。
在您的产品模型中,如下所示:

public IList<IFormFile> Image { get; set; }

在视图中,将name="files"更改为name="Product.Image"

相关问题