2

以下の 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"/>

<%} %>

ご覧のとおり、Action と Controller はハードコーディングされています。それらを動的にする方法はありますか?

私の目標は、この部分的なビューを十分に一般的なものにして、多くの場所で使用できるようにし、そこにあるアクションとコントローラーにサブミットさせることです。

ViewData を使用できることはわかっていますが、VormViewModel をビューに渡してモデル プロパティを使用することも同様に望んでいません。

上記の2つよりも良い方法はありますか?

4

1 に答える 1

1

MVC のソース コードを確認し、System.Web.Mvc --> Mvc --> Html --> FormExtensions を調べたところ、次のようなコードを記述できることがわかりました。

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;
    }
}

これがあなたが本当に得たいものかどうかはわかりませんが、この行を変更してニーズを満たすようにすれば、それを得ることができると確信しています。お役に立てれば。

于 2010-01-29T08:03:13.413 に答える