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 是硬编码的。有没有办法让它们动态化?

我的目标是让这个局部视图足够通用,以便我可以在很多地方使用它,并将它提交给它所在的 Action 和 Controller。

我知道我可以使用 ViewData,但我真的不想这样做,同样将 VormViewModel 传递给视图并使用模型属性。

有没有比我上面列出的两个更好的方法?

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 回答