TempData не отображает сообщение после успешного создания в ASP.NET MVC и не может редактировать по идентификатору, поскC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 TempData не отображает сообщение после успешного создания в ASP.NET MVC и не может редактировать по идентификатору, поск

Сообщение Anonymous »

Проблема в том, что когда категория создана успешно, она загружает только анимацию выполнения toastr.js, но не показывает сообщение, но если я раскомментирую TempData["success"] или TempData["error"] в index.cshtml, тогда он работает для index.cshtml, но поскольку я создал для этого частичное представление, я сохраняю частичное представление в _Layout .cshtml, но он показывает только анимацию, но не загружает сообщение, и я также не могу редактировать данные в index.cshtml с помощью TempData, поскольку он не содержит идентификатор.
В 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 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)
{



toastr.options = {
"progressBar": true
};
toastr.success('@TempData["success"]');

}

@if (TempData["error"] != null)
{



toastr.options = {
"progressBar": true
};
toastr.error('@TempData["error"]');

}
В POS Software\POS Software\Views\Shared\_Layout.cshtml:

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



@RenderBody()


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

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

@model IEnumerable



Categories Data
[[email protected](]
[i][/i]  Add Category
[/url]








@if (TempData["CategoryId"] != null)
{
Edit Category
}
else
{
Add New Category
}







Category Name




Dismiss
Save








@* @if (TempData["success"] != null)
{
@TempData["success"]
}

@if (TempData["error"] != null)
{
@TempData["error"]
} *@




S/N
Category Name
Created At
Action



@{
int index = 1;
}

@foreach (var category in Model)
{

@index
@category.CategoryName
@category.CreatedAt.ToString("yyyy-MM-dd")

[[email protected](]Edit[/url]


index++;
}





Не показывает сообщение после успешного создания:
[img]https://i.sstatic. net/AJIrnMe8.png[/img]

И я нажимаю «Изменить», название категории не отображается:
Изображение


Подробнее здесь: https://stackoverflow.com/questions/791 ... vc-and-can
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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