在 ASP.NET MVC 中成功创建 TempData 后不显示消息,并且无法通过 id 进行编辑,因为 TempData 未保存数据

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

问题是当类别创建成功时,它只加载

toastr.js
的进度动画而不显示消息,但是如果我取消注释
TempData["success"]
中的
TempData["error"]
index.cshtml
,那么它就可以工作对于
index.cshtml
,但由于我为此创建了部分视图,所以我将部分视图保留在
_Layout.cshtml
中,但它只显示动画而不加载消息,而且我也无法编辑
index.cshtml
中的数据通过
TempData
,因为它没有持有 id。

POS Software\POS Software\Areas\Admin\Controllers\CategoryController

using Microsoft.AspNetCore.Mvc;
using POS.DataAccess.Repository.IRepository;
using POS.Models;

namespace POS_Software.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class CategoryController : Controller
    {
        private readonly IUnitOfWork _unitOfWork;

        public CategoryController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public IActionResult Index()
        {
            List<Category> objCategoryList = _unitOfWork.Category.GetAll().ToList();
            return View(objCategoryList);
        }

        // GET: Upsert action to prepare the modal for edit or creation
        [HttpGet]
        public IActionResult Upsert(Guid? id)
        {
            Category category = new Category();

            if (id.HasValue)
            {
                category = _unitOfWork.Category.Get(c => c.Id == id.Value);
                if (category == null)
                {
                    return NotFound();
                }
            }

            // Store the retrieved category or new category in TempData
            TempData["CategoryId"] = category.Id;
            TempData["CategoryName"] = category.CategoryName;

            // Redirect to Index to open the modal with the data
            return RedirectToAction("Index");
        }

        // POST: Upsert action for creation or update
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Upsert(Category category)
        {
            //Console.WriteLine($"CategoryName: {category.CategoryName}");
            //Console.WriteLine($"CategoryId: {category.Id}");

            if (!ModelState.IsValid)
            {
                //foreach (var key in ModelState.Keys)
                //{
                //    var state = ModelState[key];
                //    foreach (var error in state.Errors)
                //    {
                //        Console.WriteLine($"Error in '{key}': {error.ErrorMessage}");
                //    }
                //}
                TempData["error"] = "Invalid category data. Please check the inputs.";
                return RedirectToAction("Index");
            }

            if (category.Id == Guid.Empty)
            {
                category.Id = Guid.NewGuid();
                category.CreatedAt = DateTime.Now;
                _unitOfWork.Category.Add(category);
                TempData["success"] = "Category created successfully.";
            }
            else
            {
                var existingCategory = _unitOfWork.Category.Get(c => c.Id == category.Id);

                if (existingCategory == null)
                {
                    TempData["error"] = "Category not found.";
                    return RedirectToAction("Index");
                }

                existingCategory.CategoryName = category.CategoryName;
                _unitOfWork.Category.Update(existingCategory);
                TempData["success"] = "Category updated successfully.";
            }

            _unitOfWork.Save();

            return RedirectToAction("Index");
        }
    }
}

POS Software\POS Software\Views\Shared\_Notification.cshtml

@if (TempData["success"] != null)
{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script type="text/javascript">
        toastr.options = {
            "progressBar": true
        };
        toastr.success('@TempData["success"]');
    </script>
}

@if (TempData["error"] != null)
{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script type="text/javascript">
        toastr.options = {
            "progressBar": true
        };
        toastr.error('@TempData["error"]');
    </script>
}

POS Software\POS Software\Views\Shared\_Layout.cshtml

<div class="container-fluid pt-4 px-4">
    <div class="row g-4">
        <partial name="_Notification" />
        @RenderBody()
    </div>
</div>

POS Software\POS Software\Areas\Admin\Views\Category\Index.cshtml

@model IEnumerable<POS.Models.Category>

<div class="container mt-4">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Categories Data</h5>
            <a href="@Url.Action("Upsert", "Category")" class="btn btn-primary" style="box-shadow: none" data-bs-toggle="modal" data-bs-target="#categoryModal">
                <i class="fas fa-plus-circle"></i> &nbsp;Add Category
            </a>

            <!-- Modal for Create/Update Category -->
            <div class="modal fade" id="categoryModal" tabindex="-1" aria-labelledby="categoryModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                        <form asp-controller="Category" asp-action="Upsert" method="post">
                            <div class="modal-header">
                                <h5 class="modal-title" id="categoryModalLabel">
                                    @if (TempData["CategoryId"] != null)
                                    {
                                        <span>Edit Category</span>
                                    }
                                    else
                                    {
                                        <span>Add New Category</span>
                                    }
                                </h5>
                                <button type="button" style="box-shadow: none" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <!-- Hidden Field for Id -->
                                <input type="hidden" id="Id" name="Id" value="@(TempData["CategoryId"] ?? Guid.Empty.ToString())" />


                                <div class="mb-3">
                                    <label for="CategoryName" class="form-label fw-bold ms-1">Category Name</label>
                                    <input type="text" class="form-control" id="CategoryName" name="CategoryName"
                                           value="@TempData["CategoryName"]" required placeholder="Category Name" />
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Dismiss</button>
                                <button type="submit" class="btn btn-success">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Success/Error Messages -->
        @* @if (TempData["success"] != null)
        {
            <div class="alert alert-success">@TempData["success"]</div>
        }

        @if (TempData["error"] != null)
        {
            <div class="alert alert-danger">@TempData["error"]</div>
        } *@

        <div class="card-body">
            <table class="table table-bordered">
                <thead class="thead-light">
                    <tr>
                        <th>S/N</th>
                        <th>Category Name</th>
                        <th>Created At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    @{
                        int index = 1;
                    }

                    @foreach (var category in Model)
                    {
                        <tr>
                            <td>@index</td>
                            <td>@category.CategoryName</td>
                            <td>@category.CreatedAt.ToString("yyyy-MM-dd")</td>
                            <td>
                                <a href="@Url.Action("Upsert", "Category", new { id = category.Id })"
                                   class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#categoryModal">Edit</a>
                            </td>
                        </tr>
                        index++;
                    }
                </tbody>
            </table>
        </div>
    </div>
</div>

创建成功后不显示消息:

not showing message

我点击编辑,它没有显示类别名称:

edit not working

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

1.部分视图中的TempData:TempData通常用于存储下一个请求的数据,但它可能无法与部分视图无缝配合,因为部分视图不会触发完整的请求周期。在这种情况下,TempData 值不会按预期转移到部分视图。

2.Toastr.js 消息未显示:由于动画正在显示,但没有渲染消息,这可能表明 JavaScript 代码未正确处理或显示消息内容。

3.无法使用 TempData 编辑 Index.cshtml 中的数据:TempData 无法正确保留您在 Index.cshtml 中编辑的 ID,这可能表明数据传递方式或页面生命周期如何与部分视图配合使用存在问题。

© www.soinside.com 2019 - 2024. All rights reserved.