Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c# - Can EditorFor() be used to create <input type="file">?

Given this model, is it possible to use the Html.EditorFor() to render a file upload input element to the page? I played around with the Datatype of the property FileName, and it was definitely impacting the editor form rendered.

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

    public String  FileName { get; set; }
}

Strongly Typed *.aspx page looks like this

    <div class="editor-field">
        <%: Html.EditorFor(model => model.FileName) %>
        <%: Html.ValidationMessageFor(model => model.FileName) %>
    </div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It would make more sense to use HttpPostedFileBase to represent an uploaded file on your view model instead of 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; }
}

then you could have the following view:

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

And finally define the corresponding editor template inside ~/Views/Shared/EditorTemplates/HttpPostedFileBase.ascx:

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

Now the controller might look like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...