ASP.Net MVC - post from one controller to another (action to action)

前端 未结 5 1761
孤街浪徒
孤街浪徒 2021-02-08 00:47

Is is possible to do a post from an Action \"Save\" in a controller \"Product\" to an Action \"SaveAll\" in a controller \"Category\"??

And also passing

5条回答
  •  面向向阳花
    2021-02-08 01:44

    Since POST is a verb for an HTTP request, this only makes sense (as written) if the .Save() method initiates an HTTP loopback connection to the appropriate .SaveAll(), (like http://..../Category/SaveAll) route and passes the form collection as part of the request. This is silly and not recommended, since this will break your ability to unit test this controller.

    If, however, you mean that you want to call .SaveAll() and return its rendered result back to the client, you could use .RenderAction() and pass the model or form collection received by .Save() as the parameter.

    Or, on the server side, just instantiate the Category controller and call its .SaveAll() method, again passing the model received by .Save() as the parameter.

    public ActionResult Save(MyModel m)
    {
        Category cat = new Category();
    
        return cat.SaveAll(m);
    }
    

    However, you'll have to take the result from that call and make sure it's handled properly by the resulting view.

    If this is what you're trying to do, it's worth noting that you should really have the code of the .SaveAll() method that performs the save separated into a dedicated business logic layer rather than living in the controller. All of this functionality should, in theory, be available for use in a different controller, or in a library that could be included in other applications.

提交回复
热议问题