2010-01-29 79 views
2

如果我有以下PartialViewPartialView動態BeginForm參數

<%@ 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"/> 

<%} %> 

正如你所看到的,動作和控制器硬編碼。有什麼辦法可以讓他們變成動態的嗎?

我的目標是讓這個局部視圖足夠通用,以便我可以在很多地方使用它,並將它提交給坐在其中的動作和控制器。

我知道我可以使用ViewData,但實際上並不希望將VormViewModel傳遞給視圖並使用模型屬性。

有沒有比我上面列出的兩個更好的方法?

回答

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

我我不確定這正是你真正想要得到的,但是如果你改變這些方式以滿足你的需求,我相信你可以得到它。 希望這有助於。