views:

146

answers:

1

If I have the below PartialView

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Models.Photo>" %>

<% using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))   { %>

    <%= Html.EditorFor( c => c.Caption ) %>

    <div class="editField">
        <label for="file" class="label">Select photo:</label>
        <input type="file" id="file" name="file" class="field" style="width:300px;"/>
    </div>

  <input type="submit" value="Add photo"/>

<%} %>

As you can see, the Action and the Controller are hard coded. Is there a way I can make them dynamic?

My goal is to have this partial view generic enough that I can use it in many places and have it submit to the Action and Controller it is sitting within.

I know I can use ViewData but really don't want to and likewise with passing a VormViewModel to the view and using the model properties.

Is there a nicer way than the two I listed above?

+1  A: 

I Checked the source code of MVC and dig into the System.Web.Mvc --> Mvc --> Html --> FormExtensions so I find you can write some code like :

public static class FormHelpers
{
    public static MvcForm BeginFormImage(this HtmlHelper htmlHelper,  IDictionary<string, object> htmlAttributes)
    {
        string formAction = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
        return FormHelper(htmlHelper, formAction, FormMethod.Post, htmlAttributes);
    }

    public static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
    {
        TagBuilder tagBuilder = new TagBuilder("form");
        tagBuilder.MergeAttributes(htmlAttributes);
        // action is implicitly generated, so htmlAttributes take precedence.
        tagBuilder.MergeAttribute("action", formAction);
        tagBuilder.MergeAttribute("enctype", "multipart/form-data");
        // method is an explicit parameter, so it takes precedence over the htmlAttributes.
        tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
        htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
        MvcForm theForm = new MvcForm(htmlHelper.ViewContext);

        if (htmlHelper.ViewContext.ClientValidationEnabled)
        {
            htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];
        }

        return theForm;
    }
}

I'm not sure this is exactly what you really want to get but I'm sure you can get it if you change this lines in way satisfies your needs. Hope this helps.

ali62b