views:

286

answers:

1

If you look at the NerdDinner example of creating and editing dinners then you see they use a partial (ViewUserControl or ASCX) DinnerForm to put the functionality of creating and editing dinners into one file because it is essential the same and they use it using RenderPartial("DinnerForm").

This approach seems fine for me but I've run into a problem where you have to add additonal route values or html properties to the Form tag.

This picks up the current action and controller automatically:

<% using (Html.BeginForm()) { %>

However, if I use another BeginForm() overload which allows to pass in enctype or any other attribute I have to do it like this:

<% using ("Create", "Section", new { modal = true }, FormMethod.Post, new { enctype = "multipart/form-data" }))

and as you can see we lose the ability to automatically detect in which View we are calling RenderPartial("OurCreateEditFormPartial"). We can't have hardcoded values in there because in Edit View this postback will fail or won't postback to the right controller action.

What should I do in this case?

+3  A: 

What about adding the following HTML helpers:

    public static MvcHtmlString CurrentAction(this HtmlHelper htmlHelper)
    {
        return htmlHelper.ViewContext.RouteData.Values["action"];
    }

    public static MvcHtmlString CurrentController(this HtmlHelper htmlHelper)
    {
        return htmlHelper.ViewContext.RouteData.Values["controller"];
    }

Then you could go something like this:

<% using (Html.CurrentAction, Html.CurrentController, new { modal = true }, FormMethod.Post, new { enctype = "multipart/form-data" }))

Its not 100% perfect but you could also add an additional HTML helper which would streamline it a little more:

public static MvcForm BeginForm(this HtmlHelper htmlHelper, object routeValues, FormMethod method, object htmlAttributes)
{
    return htmlHelper.BeginForm(Html.CurrentAction, Html.CurrentController, routeValues, method, htmlAttributes);
}

Let me know if this helps. Cheers

anthonyv
this definitely does help but it looks a bit of a stretch. The thing is, every other day I run into another special case where I have to write some custom helpers or extensions to achieve some basic functionality which should already be there but apparently ASP.NET MVC designers missed it. I am wondering how much longer will this continue to happen to me. ;)
mare
90% of the MVC "helpers" you see floating around the net or on SO is just semantic sugar that only shorten otherwise lengthy calls. Did the MVC team "miss" anything here. Most of the time what you need is right in front of you, just have to know where to look.
jfar
I agree with jfar... 90% of the time it does what I want it to do but I love the fact that I can seamlessly add in the functionality that I need when its not there, the above being a point in case.
anthonyv