如何將重復的代碼部分從控制器移到 Helper Method 類中,而不必在 .NET Core 中重復代碼?如果我需要提供更多詳細資訊,請告訴我。
我需要將任何重復代碼部分移出此控制器,以便我可以在需要它的所有其他控制器中呼叫此方法
用戶控制器:
using myApp.Data;
using myApp.Models;
using myApp.Models.ViewModels;
using myApp.Utilities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace myApp.Controllers
{
[Authorize]
public class UserController : Controller
{
private readonly ApplicationDbContext db;
private readonly UserManager<ApplicationUser> userManager;
public UserController( ApplicationDbContext db,
UserManager<ApplicationUser> userManager)
{
this.db = db;
this.userManager = userManager;
}
[HttpGet]
public async Task<IActionResult> UpdateUserDetails(UpdateUserViewModel model)
{
if (ModelState.IsValid)
{
var user = await userManager.FindByIdAsync(model.Id);
if (user == null)
{
//Calling Repeated Code in this controller
return UserNotFound();
}
else
{
user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.UserName = model.UserName;
user.PhoneNumber = model.PhoneNumber;
}
var result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
//Calling Repeated Code in this controller
return UpdateSuccess();
}
AddErrors(result);
}
return View(model);
}
//REPEATED CODE SECTION BEGINS (Extracted out of UpdateUserDetails Controller)
public IActionResult UserNotFound()
{
TempData[HelperStatic.ErrorMessage] = HelperStatic.userNotFoundMsg;
return View(HelperStatic.notFoundView);
}
public IActionResult UpdateSuccess()
{
TempData[HelperStatic.SuccessMessage] = HelperStatic.recordUpdatedMsg;
return RedirectToAction(nameof(Index));
}
//REPEATED CODE SECTION ENDS
}
}
專案中已經存在一個靜態助手類,它只有靜態常量。
上面控制器中使用的靜態助手類:
namespace myApp.Utilities
{
public static class HelperStatic
{
// Messages
public const string SuccessMessage = "Success";
public const string ErrorMessage = "Error";
public const string userNotFoundMsg = "User not found";
public const string recordUpdatedMsg = "Record updated";
// Views
public const string notFoundView = "NotFound";
}
}
我需要一個HelperMethod具有可重用操作方法的不同類。我如何實作這一目標?
uj5u.com熱心網友回復:
創建一個控制器基類并將所有實用程式方法移到其中,而不是一個幫助器類。
public class BaseController : Controller
{
public IActionResult UserNotFound()
{
TempData[HelperStatic.ErrorMessage] = HelperStatic.userNotFoundMsg;
return View(HelperStatic.notFoundView);
}
public IActionResult UpdateSuccess()
{
TempData[HelperStatic.SuccessMessage] = HelperStatic.recordUpdatedMsg;
return RedirectToAction(nameof(Index));
}
}
你可以像這樣使用它。
public class HomeController : BaseController
{
public IActionResult Index()
{
UserNotFound();
return View();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385973.html
標籤:C# asp.net核心 .net核心 asp.net-core-mvc .net-6.0
