如何打开 ASP.NET Core MVC 中区域内找到的页面?

问题描述 投票:0回答:1

当我按下按钮

Products
进入产品页面时,我得到http 404页面。

我在 ASP.NET Core 中创建了新区域并添加了

ProductController
:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Project.ECommerceDbContext;
using Project.Models.ProjectClasses;

namespace Project.Areas.about.Controllers
{
    [Area("about")]
    public class ProductsController : Controller
    {
        private readonly ECommerce _CONTEXT;

        public ProductsController(ECommerce CONTEXT)
        {
            _CONTEXT = CONTEXT;
        }

        public IActionResult product()
        {
            IEnumerable<Product> Viewproduct = _CONTEXT.Products.ToList();
            return View(Viewproduct);
        }

        public void Selectecategorywithproduct(int selected = 0)
        {
            List<Category> category = _CONTEXT.Categories.ToList();
            SelectList listItems = new SelectList(category, "Id", "Name", selected);
            ViewBag.SelectedList = listItems;
        }

        public IActionResult Add_Item()
        {
            Selectecategorywithproduct();
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Add_Item(Product Newproduct)
        {
            if (ModelState.IsValid)
            {
                var category = _CONTEXT.Categories.Find(Newproduct.IDCategory);

                 if (category?.Id != null) // تحقق من وجود الفئة المحددة
                {
                    _CONTEXT.Products.Add(Newproduct);
                    _CONTEXT.SaveChanges();
                    TempData["AddNewProduct"] = $"The product {Newproduct.Name} has been added successfully";
                    return RedirectToAction(nameof(product));
                }
                else
                {
                    ModelState.AddModelError("IDCategory", "Please select a valid category");
                    Selectecategorywithproduct();
                }
                //}
            }

            return View(Newproduct);
        }

        public IActionResult Edit_Item(int? id)
        {
            if (id == null || id == 0)
                return NotFound();

            var product = _CONTEXT.Products.SingleOrDefault(p => p.ProducId == id);

            if (product == null)
                return NotFound();

            ViewData["Categories"] = new SelectList(_CONTEXT.Categories.ToList(), "Id", "Name", product.IDCategory);
            Selectecategorywithproduct();

            return View(product);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit_Item(int? id, Product Editproduct)
        {
            var products = _CONTEXT.Products.SingleOrDefault(p => p.ProducId == id);

            if (ModelState.IsValid)
            {
                products!.Name = Editproduct.Name;
                products.Price = Editproduct.Price;
                products.Quantity = Editproduct.Quantity;
                products.Added_Date = Editproduct.Added_Date;
                products.IDCategory = Editproduct.IDCategory;
                _CONTEXT.Products.Update(products);
                _CONTEXT.SaveChanges();
                TempData["EditProduct"] = $"The product {products.Name} has been edited successfully";

                return RedirectToAction("product");
            }

            ViewData["Categories"] = new SelectList(_CONTEXT.Categories.ToList(), "Id", "Name", Editproduct.IDCategory);

            return View(Editproduct);
        }

        public IActionResult Delete_Item(int? id)
        {
            if (id == null || id == 0)
                return NotFound();

            var product = _CONTEXT.Products.SingleOrDefault(p => p.ProducId == id);

            if (product == null)
                return NotFound();

            return View(product);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Delete_Item(int? id, Product Deleteproduct)
        {
            var products = _CONTEXT.Products.SingleOrDefault(p => p.ProducId == id);

            if (ModelState.IsValid)
            {
                _CONTEXT.Products.Remove(products!);
                _CONTEXT.SaveChanges();
                TempData["DeleteProduct"] = $"The product {products?.Name} has been deleted successfully";
                return RedirectToAction("product");
            }
            else
                return View(Deleteproduct);
        }
    }
}

Add_Item
查看:

@using Project.Models.ProjectClasses;
@model Product
@{
    ViewData["Title"] = "Add Item";
}
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Add Item</h1>

<form method="post" action="product">
    <fieldset>
        <div class="form-group">
            <label asp-for="Name" class="form-label mt-4">Product Name</label>
            <input class="form-control" asp-for="Name" placeholder="Enter Product Name">
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Price" class="form-label mt-4">Price</label>
            <input class="form-control" asp-for="Price" placeholder="Price">
            <span asp-validation-for="Price" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Quantity" class="form-label mt-4">Quantity</label>
            <input class="form-control" asp-for="Quantity" placeholder="Quantity">
            <span asp-validation-for="Quantity" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="IDCategory" class="form-label mt-4">Category ID</label>
            <select class="form-control" asp-for="IDCategory" asp-items="ViewBag.SelectedList">
                <option value="0">Selecte Category</option>

            </select>
            <input type="hidden" asp-for="IDCategory" value="" />

            <span asp-validation-for="IDCategory" class="text-danger"></span>

        </div>
        <p></p>
        <button type="submit" asp-for="saveButton" class="btn btn-primary"><i class="bi bi-check2-all"></i> Save</button>
        <a asp-area="about" asp-controller="Products" asp-action="product" class="btn "><i class="bi bi-backspace"></i> Go Back</a>
    </fieldset>

</form>
@section Scripts
    {
    <partial name="_ValidationScriptsPartial" />

}

Edit_Item
查看:

@using Project.Models.ProjectClasses;
@model Product
@{
    ViewData["Title"] = "Edit_Item";
}
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Edit_Item</h1>

<form method="post">
    <fieldset>
        <div class="form-group">
            <label asp-for="Name" class="form-label mt-4">Product Name</label>
            <input class="form-control" asp-for="Name" placeholder="Enter Product Name">
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Price" class="form-label mt-4">Price</label>
            <input class="form-control" asp-for="Price" placeholder="Price">
            <span asp-validation-for="Price" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Quantity" class="form-label mt-4">Quantity</label>
            <input class="form-control" asp-for="Quantity" placeholder="Quantity">
            <span asp-validation-for="Quantity" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="IDCategory" class="form-label mt-4">Category ID</label>
            <select class="form-control" asp-for="IDCategory" asp-items="ViewBag.SelectedList">
                <option value="0">Selecte Category</option>
            </select>
            <input type="hidden" asp-for="IDCategory" value="" />
            <span asp-validation-for="IDCategory" class="text-danger"></span>
        </div>
        <p></p>
        <button type="submit" class="btn btn-primary"><i class="bi bi-clipboard-check-fill"></i> Update </button>
        <a asp-area="about" asp-controller="Products" asp-action="product" class="btn "><i class="bi bi-backspace"></i> Go Back</a>
    </fieldset>
</form>
@section Scripts
    {
    <partial name="_ValidationScriptsPartial" />
}

Delete_Item
查看:

@using Project.Models.ProjectClasses;
@model Product
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Confirm deletion</h2>
<p>Are you sure you want to delete this product?</p>
<form method="post" asp-action="Delete_Item">
    <button type="submit" class="btn btn-danger">Yes, delete</button>
    <a asp-area="about" asp-controller="Products" asp-action="product" class="btn btn-secondary cancel-btn">Cancel</a>
</form>

<script>
    $(document).ready(function () {

        $(".delete-btn").on("click", function () {
            var productId = $(this).data("product-id");
            var deleteUrl = "/Products/DeleteConfirmation/" + productId;
            $("#delete-modal-body").load(deleteUrl, function () {
                $("#delete-modal").modal("show");
            });
        });


        $(".cancel-btn").on("click", function () {
            $("#delete-modal").modal("hide");
        });
    });

</script>

以及产品列表视图:

@using Project.Models.ProjectClasses;
@model IEnumerable<Product>
@{
    ViewData["Title"] = "product";
}
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>product</h1>
<div>
    @if (TempData["AddNewProduct"] != null)
    {
        <div id="addProductMessage" class="alert alert-@TempData["AddNewProduct"]" role="alert" style="color:aquamarine">
            @TempData["AddNewProduct"]
        </div>
        <audio asp-for="audioPlayer" controls style="display: none;" autoplay>
            <source src="~/audio/sucess sound.mp3" type="audio/mpeg">
            Your browser does not support the audio element.
        </audio>
        <script>
            setTimeout(function () {
                $("#addProductMessage").fadeOut("slow", function () {
                    $(this).remove();
                });
            }, 7000);
            document.getElementById("addProductMessage").addEventListener("show", function () {
                var audioPlayer = document.getElementById("audioPlayer");
                audioPlayer.play();
            });
        </script>
    }

    @if (TempData["EditProduct"] != null)
    {
        <div id="editProductMessage" class="alert alert-@TempData["EditProduct"]" role="alert" style="color:aquamarine">
            @TempData["EditProduct"]
        </div>
        <audio asp-for="audioPlayer" controls style="display: none;" autoplay>
            <source src="~/audio/edit sound.mp3" type="audio/mpeg">
            Your browser does not support the audio element.
        </audio>
        <script>
            setTimeout(function () {
                $("#editProductMessage").fadeOut("slow", function () {
                    $(this).remove();
                });
            }, 3000);
            document.getElementById("editProductMessage").addEventListener("show", function () {
                var audioPlayer = document.getElementById("audioPlayer");
                audioPlayer.play();
            });
        </script>
    }
    @if (TempData["DeleteProduct"] != null)
    {
        <div id="deleteProductMessage" class="alert alert-@TempData["DeleteProduct"]" role="alert" style="color:red">
            @TempData["DeleteProduct"]
        </div>
        <audio asp-for="audioPlayer" controls style="display: none;" autoplay>
            <source src="~/audio/delete.mp3" type="audio/mpeg">
            Your browser does not support the audio element.
        </audio>
        <script>
            setTimeout(function () {
                $("#deleteProductMessage").fadeOut("slow", function () {
                    $(this).remove();
                });
            }, 3000);
            document.getElementById("deleteProductMessage").addEventListener("show", function () {
                var audioPlayer = document.getElementById("audioPlayer");
                audioPlayer.play();
            });
        </script>
    }

    <div class="text-end">
        <a asp-area="about" asp-controller="Products" asp-action="Add_Item" class="btn btn-success">Add new item</a>
    </div>
    
    <table class="table table-hover">
        <thead>
            <tr class="table-primary">
                <th scope="row"></th>
                <th>Product Name</th>
                <th>Product Categroy</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Added Date</th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var product in Model)
            {
                <tr class="table-light">
                    <td>@product.ProducId</td>
                    <td>@product.Name</td>
                    <td>
                        @if (product.IDCategory == null || product.IDCategory == 0)
                        {
                            <span>Not select</span>
                        }
                        else
                        {
                            @product.category!.Name
                        }
                    </td>

                    <td>$ @product.Price</td>
                    <td>@product.Quantity</td>
                    <td>@product.Added_Date</td>
                    <td>

                        <a asp-area="about" asp-controller="Products" asp-action="Edit_Item" asp-route-id="@product.ProducId" class="btn btn-success"><i class="bi bi-pencil"></i> Edit</a>
                        <a asp-area="about" asp-controller="Products" asp-action="Delete_Item" asp-route-id="@product.ProducId" class="btn btn-danger"><i class="bi bi-trash3"></i> Delete</a>
                    </td>
                    <td></td>
                </tr>
            }
        </tbody>
    </table>
</div>

当我按下“产品”按钮进入产品页面时,会显示 404 页面,但如果我在 URL 源中写入该页面,它将起作用,而其他页面我想要解决方案。

这个视频将向您展示更多细节

youtube

c# entity-framework asp.net-core asp.net-core-mvc
1个回答
0
投票

这是一个路由问题,因为您生成的 URL 仅指向控制器名称(产品)。相反,它们必须指向“关于/产品”。 因此,打开项目的“Program.cs”文件,并以这种方式修改以“app.MapControllerRoute(”:

开头的代码行
app.MapControllerRoute(
    name: "default",
    pattern: "about/{controller=Home}/{action=Index}/{id?}");
© www.soinside.com 2019 - 2024. All rights reserved.