views:

289

answers:

3

I have a partial view that is rendered by several views which are returned by several action methods.

The partial view has a form that should post back to the called action method.

It is my understanding that if i just call

<% Html.BeginForm(); %>

from within a view, the form's action attribute will point to the called action method. I can't do this, because I need to set the form's ID attribute for javascript purposes. The overload of Html.BeginForm that will let me set html attributes also requires an explicit controller and action. So, instead of using the Html helper, I could just write the form element out like:

<form action="<%=(NEED TO SOMEHOW GET THE URL TO THE CURRENT ACTION) %>" method="post" id="myForm">

I'm just not sure how to get the URL.

+1  A: 

In that situation, I would probably just have the controller (or the parent view) put the appropriate destination URL in your model/ViewData.

As for HOW, inside your controller:

public ActionResult MyAction() {
    MyModel m = new MyModel();

    ...

    m.MyControlAction = "MyAction";
    m.MyControlController = "MyController";

    return View("MyView", m);
}

Then in your view:

Html.RenderPartial("MyControl", ViewData.Model);

And in your partial view:

Html.BeginForm(ViewData.Model.MyControlController, ViewData.Model.MyControlAction, ...)

For a cleaner design, you would probably want to have the MyControlController and MyControlAction members come fron an interface that each Model that uses that control must implement. Then have the partial view take a strongly typed model with that interface type.

Eric Petroelje
agreed, it seems that adding this to the viewdata would be the most straight forward thing to do.
Amir
Craig's answer worked for me, but how can you get the current url in the controller? If I were going to do that I would probably store the url in viewdata from an overridden onactionexecuting method, so that I wouldn't have to keep doing it in every action method.
Ronnie Overby
@Ronnie - You don't need the current URL per-se, you just need the current controller and action - which of course you would know when you are inside the action method of a controller :)
Eric Petroelje
@Eric - Yes, but it would be better to do this in OnActionExecuting, where I wouldn't know the action.
Ronnie Overby
+2  A: 

Just pass null for the controller and action. The correct values will be substituted. E.g.:

<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "employeeGroupForm" }))
Craig Stuntz
+1 - Sure, there's my way, and then there's the easy way :)
Eric Petroelje
Made me laugh! :)
Craig Stuntz
A: 

ViewContext.RouteData.Values["action"]

Or something similar gets the job done

AndreasN
I don't know the action at design time.
Ronnie Overby
Sorry corrected the call, that gets the action value from the routeData used to find the correct action.
AndreasN