c# - 在 asp.net mvc3 中重构 Controller 的操作

标签 c# asp.net-mvc asp.net-mvc-3 refactoring

我正在为不同的模型编写此操作代码(在同一 Controller 内)超过10次。有什么方法可以减少此代码或者如何创建通用操作。

    [HttpPost]
    public ActionResult SavePerson(Person p)
    {
        if (ModelState.IsValid)
        {
            //do something
            return Redirect("/Main");
        }
        else
        {
            return View();
        }
    }


    [HttpPost]
    public ActionResult SaveCategory(Category c)
    {
        if (ModelState.IsValid)
        {
            //do something
            return Redirect("/Main");
        }
        else
        {
            return View();
        }
    }

最佳答案

要点是 //do some 部分始终因操作而异。因此,让我们尝试减少除此之外的所有代码。您可以使用基本 Controller 来实现它

public class BaseController : Controller
{
    [NonAction]
    protected virtual ActionResult HandlePost<T>(T model, Action<T> processValidModel)
    {
        if (ModelState.IsValid)
        {
            processValidModel(model);
            return RedirectToAction("Main");
        }
        else
        {
            return View(model);
        }
    }
}

在派生 Controller 中

public class DerivedController : BaseController
{
    [HttpPost]
    public ActionResult Create(Person person)
    {
       return HandlePost(person, p => _repository.Save(p));
    }
}

关于c# - 在 asp.net mvc3 中重构 Controller 的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8847644/

相关文章:

c# - 在模型级别定义具有唯一键的实体

c# - 以 double 转换字典键

c# - Entity Framework 6 代码首先处理影子属性

c# - 如何将 List<Int> 传递给 SQL Server 存储过程

asp.net-mvc - 如何保护对返回 JSON 的 MVC 操作的访问

asp.net-mvc-3 - MVC 删除记录,但如何在 Controller 中对此进行编码

c# - ProjectGuid(.csproj),如何正确生成?

mysql - 错误未知列 'Extent1.id' in 'where clause' 在 mysql 和 EF6 列表的位置

asp.net-mvc-3 - ViewModel 的注意事项

visual-studio-2010 - Entity Framework 不创建数据库