24

このモデルでは、Html.EditorFor()を使用してファイルアップロード入力要素をページにレンダリングすることは可能ですか?プロパティFileNameのデータ型を試してみましたが、レンダリングされたエディターフォームに間違いなく影響を与えていました。

public class DR405Model
{
    [DataType(DataType.Text)]
    public String TaxPayerId { get; set; }
    [DataType(DataType.Text)]
    public String ReturnYear { get; set; }

    public String  FileName { get; set; }
}

強く入力された*.aspxページは次のようになります

    <div class="editor-field">
        <%: Html.EditorFor(model => model.FileName) %>
        <%: Html.ValidationMessageFor(model => model.FileName) %>
    </div>
4

4 に答える 4

39

次の代わりに、 HttpPostedFileBaseを使用して、ビュー モデルでアップロードされたファイルを表す方が理にかなっていstringます。

public class DR405Model
{
    [DataType(DataType.Text)]
    public string TaxPayerId { get; set; }

    [DataType(DataType.Text)]
    public string ReturnYear { get; set; }

    public HttpPostedFileBase File { get; set; }
}

次に、次のビューを持つことができます。

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

    ... input fields for other view model properties

    <div class="editor-field">
        <%= Html.EditorFor(model => model.File) %>
        <%= Html.ValidationMessageFor(model => model.File) %>
    </div>

    <input type="submit" value="OK" />
<% } %>

最後に、対応するエディター テンプレートを内部で定義します~/Views/Shared/EditorTemplates/HttpPostedFileBase.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<input type="file" name="<%: ViewData.TemplateInfo.GetFullHtmlFieldName("") %>" id="<%: ViewData.TemplateInfo.GetFullHtmlFieldId("") %>" />

コントローラーは次のようになります。

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new DR405Model());
    }

    [HttpPost]
    public ActionResult Index(DR405Model model)
    {
        if (model.File != null && model.File.ContentLength > 0)
        {
            var fileName = Path.GetFileName(model.File.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
            model.File.SaveAs(path);
        }

        return RedirectToAction("Index");
    }
}
于 2011-05-25T06:33:29.197 に答える
10

MVC 5 の例を次に示します (htmlAttributes に必要)。

これを ~\Views\Shared\EditorTemplates の下に HttpPostedFileBase.cshtml という名前のファイルとして作成します。

@model HttpPostedFileBase
@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
    htmlAttributes["type"] = "file";
}
@Html.TextBoxFor(model => model, htmlAttributes)

これにより、正しい ID と名前を持つコントロールが生成され、モデルの EditorFor テンプレートからコレクションを編集するときに機能します。

于 2015-11-17T10:48:01.540 に答える
6

追加:htmlAttributes = new { type = "file" }

<div class="editor-field">
    <%: Html.EditorFor(model => model.FileName, new { htmlAttributes = new { type = "file" }}) %>
    <%: Html.ValidationMessageFor(model => model.FileName) %>
</div>

注: 私は MVC 5 を使用しています。他のバージョンではテストしていません。

于 2017-01-30T12:59:00.123 に答える
0

いいえ、http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspxをご覧ください

于 2011-05-24T16:08:57.557 に答える