gpt4 book ai didi

c# - 创建通用的 ActionResult

转载 作者:太空狗 更新时间:2023-10-29 23:33:26 24 4
gpt4 key购买 nike

我的 Controller 中有以下内容;

    public ActionResult CocktailLoungeBarAttendant()
{
return View();
}

[HttpPost]
public ActionResult cocktailLoungebarattendant(string name, string email, string phone)
{
return View();
}

public ActionResult merchandisecoordinator()
{
return View();
}

[HttpPost]
public ActionResult merchandisecoordinator(string name, string email, string phone)
{
return View();
}

这只发生了 4 次,但让我感到困扰的是我将代码重复了 4 次。

然后我有一个 BaseController,它可以获取参数并对它们进行处理;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
{

我希望能够取消 Post ActionResult,并在基本 Controller say 中有一个。

这可能吗?

最佳答案

你可以这样做:在您的(基本) Controller 中添加:

protected override void HandleUnknownAction(string actionName)
{
var controllerName = GetControllerName();
var name = GetViewName(ControllerContext, string.Format("~/Views/{0}/{1}.cshtml",controllerName, actionName));
if (name != null)
{
var result = new ViewResult
{
ViewName = name
};
result.ExecuteResult(ControllerContext);
}
else
base.HandleUnknownAction(actionName);
}

protected string GetViewName(ControllerContext context, params string[] names)
{
foreach (var name in names)
{
var result = ViewEngines.Engines.FindView(ControllerContext, name, null);
if (result.View != null)
return name;
}
return null;
}

这将尝试检查是否存在未定义方法的 View 。我认为您可以从此处自行扩展它以满足您的需求。

关于c# - 创建通用的 ActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10221379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com