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
I would either just update your categories in your repository from your Product controller Save method directly, or refactor the Save Categories functionality in its own method, and call that from both controller methods.
public class Product : Controller
{
...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(FormCollection productValues)
{
...
RedirectToAction("SaveAll", "Category", new { formValues = productValues });
}
...
}
public class Category : Controller
{
...
public ActionResult SaveAll(FormCollection formValues)
{
...
}
}
The assumption is that you are executing the POST in the context of the Product.
Put the following code in your Product
controller:
return RedirectToAction("SaveAll", "Category")
Here, "SaveAll"
is an Action Name and "Category"
is Controller Name.
The user will then be redirected to the SaveAll
action (i.e., the method will be called).
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.
You can declare a form like this in your View and can specify whatever controller or Action you wish.
Html.BeginForm("SaveAll", "Category", FormMethod.Post);
If you are in a controller then you can use.
TempData["Model"] = Model;
RedirectToAction("SaveAll", "Category");