How to know the name of the Actionresult that called the view?

Asked

Viewed 1,071 times

5

I wonder if it’s possible to get the name of ActionResult who called the View. I know that normally View has the same name as ActionResult, but in my case, I have a single view for two ActionResult from within the View I need to know which one ActionResult will do the POST.

It would be something like:

@using (Html.BeginForm(ACTION_RESULT_QUE_CHAMOU_A_VIEW, "MeuController", FormMethod.Post, new { @class = "form-horizontal" }))

Updating

I was able to take Actionresult dynamically with:

ViewBag.ActionResult = ViewContext.RequestContext.RouteData.Values.Values.Where(w => w.Equals("Edit") || w.Equals("Create")).First().ToString();

I don’t know if it’s the best way, if it’s not please tell me.

Only now I had another problem. When I call my Beginform that way:

@using (Html.BeginForm(ViewBag.ActionResult, "MeuController", FormMethod.Post, new { @class = "form-horizontal" }))

I get the following error on the page:

Extension methods cannot be shipped dynamically. Consider converting dynamic arguments or calling the method extension without method syntax.

Someone knows how to fix this?

2 answers

4


Thus:

ActionResult Create and Edit calls the same View CreateEdit

public ActionResult Create()
{
    return View("CreateEdit");
}
public ActionResult Edit()
{
    return View("CreateEdit");
}

Automatically pick up the ActionResult who was called

@using (Html.BeginForm(Html.ViewContext.Controller.ControllerContext.RouteData.Values["action"].ToString(), 
            "Geral", 
            FormMethod.Post, 
            new { @class = "form-horizontal" }))
{               

}

If you want to take the ActionResult and the Controller put it like this?

@using (Html.BeginForm(Html.ViewContext.Controller.ControllerContext.RouteData.Values["action"].ToString(),
            Html.ViewContext.Controller.ControllerContext.RouteData.Values["controller"].ToString(),
            FormMethod.Post, 
            new { @class = "form-horizontal" }))
{

}

When posting these forms respectively will fall into your ActionResult

[HttpPost]
public ActionResult Create(FormCollection form)
{
    return RedirectToAction("Create");
}
[HttpPost]
public ActionResult Edit(FormCollection form)
{
    return RedirectToAction("Edit");
}

1

This is because you used an element of ViewBag to call the HtmlHelper.

This solves:

@using (Html.BeginForm(ViewBag.ActionResult.ToString(), "MeuController", FormMethod.Post, new { @class = "form-horizontal" })) { ... }
  • Gypsy, Thank you! That solves my last question. I marked @Harrypotter’s as an answer because his solves the whole problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.