【问题标题】:How to move from one controller to next in Asp.net MVC如何在 Asp.net MVC 中从一个控制器移动到下一个控制器
【发布时间】:2015-01-26 18:43:25
【问题描述】:

我有一个小的 asp.net mvc 应用程序,其中我的 Index.html 中的操作链接很少,home controllder 中有以下代码。

当用户点击Edit ActionLink时,它会将控制权交给 HomerController 的“Edit”动作方法(类型为 httpGet)。该操作方法的视图是 Edit.cshtml。如果我在该 EDIT 视图中进行一些数据操作..并尝试发布该数据,我该怎么办?在同一个 HomeController 中编写另一个编辑操作方法(httpPost)?那样的话我家的控制器会变大吧?

如果我需要为此编写单独的控制器,如何将控制权转移到该控制器? (我的意思是如何将我新创建的编辑控制器附加到编辑视图?)

List<StateCity> stateCityList = new List<StateCity>();
        public ActionResult Index()
        {
            StateCity sc1 = new StateCity() { Id = 1, StateName = "Dallas", Cities = new List<string>() { "ab", "cd" } };
            StateCity sc2 = new StateCity() { Id = 2, StateName = "Austin", Cities = new List<string>() { "ef", "gh" } };
            stateCityList.Add(sc1);
            stateCityList.Add(sc2);
            return View(stateCityList);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }

        public ActionResult Edit(int id)
        {
            return View();
        }

【问题讨论】:

    标签: c# asp.net-mvc controller


    【解决方案1】:

    如前所述,使用 HttpPost 属性和您的 ViewModel 作为参数再添加一个操作。

    如果您遵循 SRP 原则,您的控制器将不会增长。在我看来 HomeController 不应该有像 Edit 这样的动作。我会将它们移动到相应的控制器(例如 ArticleController)。但是 HomeController 会有 Index、About 之类的操作。

    @Html.ActionLink("Edit Article", "Edit", "Article", new { id= 587 }, new { id = "linkId" })
    

    点击此处了解更多详情:https://msdn.microsoft.com/en-us/library/dd504972(v=vs.118).aspx

    【讨论】:

    • 我不知道如何拥有另一个控制器并从 Index.cshtml 中的链接导航到该控制器。
    【解决方案2】:

    您可以使用属性为 HTTP POST 创建操作:

    [HttpPost]
    public ActionResult Edit(parameters here){}
    

    这是一个不错的example of forms in MVC

    【讨论】:

      【解决方案3】:

      通常对于编辑,您需要执行两个操作。

      一个用于加载编辑页面:

      [HttpGet]
      public ActionResult Edit(int id)
      

      还有一个用于提交表单(执行编辑):

      [HttpPost]
      public ActionResult Edit(YourModel model)
      

      如果您担心控制器方法变得太大,请考虑在应用程序的另一层中抽象逻辑/保存代码。

      【讨论】:

        猜你喜欢
        • 2018-08-16
        • 2020-11-01
        • 2019-05-13
        • 1970-01-01
        • 2016-10-04
        • 2017-09-18
        • 1970-01-01
        • 2018-05-25
        • 1970-01-01
        相关资源
        最近更新 更多