How do I know the name of ActionResult that called the view?

5

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

It would be something like:

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

Update

I was able to get ActionResult dynamically with:

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

I do not know if it's the best way, if not please, tell me.

But now I have another problem. When I call my BeginForm this way:

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

I get the following error on the page:

  

Extension methods can not be dispatched dynamically.   Consider converting the dynamic arguments or invoking the   extension without the method syntax.

Does anyone know how to solve this?

    
asked by anonymous 28.06.2014 / 16:21

2 answers

4

So:

ActionResult Create and Edit calls the same View CreateEdit

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

Automatically fetch the ActionResult that was called

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

}

If you want to get ActionResult and 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 you post these forms, respectively, they will fall in their ActionResult

[HttpPost]
public ActionResult Create(FormCollection form)
{
    return RedirectToAction("Create");
}
[HttpPost]
public ActionResult Edit(FormCollection form)
{
    return RedirectToAction("Edit");
}
    
28.06.2014 / 16:46
1

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

This resolves:

@using (Html.BeginForm(ViewBag.ActionResult.ToString(), "MeuController", FormMethod.Post, new { @class = "form-horizontal" })) { ... }
    
29.06.2014 / 00:02