开发者

Edit and Create view using EditCreate.ascx partial in ASP.NET MVC

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 abil开发者_开发百科ity 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?


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


I'm answering in an old thread because it came up number two on a Google search whilst I was looking for the same thing :) Found on this SO post:

Html.BeginForm and adding properties

With MVC3 (not sure about MVC2) you can pass null in for the action and controller and get the default routes that BeginForm() would use.

@Html.BeginForm(null, null, FormMethod.Post, new { enctype="multipart/form-data"})

Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜