如何创建MVC 4 @ Html.TextBox type ="file"?

Hei*_*del 10 asp.net-mvc asp.net-mvc-4

我需要在表单中添加以下字段

<input type="file" class="input-file" />
Run Code Online (Sandbox Code Playgroud)

我创建模型并描述这个领域(最后一个领域)

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;

 namespace CorePartners_Site2.Models
 {
     public class FeedbackForm
     {
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Company { get; set; }
    public string AdditionalInformation { get; set; }
    public HttpPostedFileBase ProjectInformation { get; set; }
     }
 }
Run Code Online (Sandbox Code Playgroud)

并创造

@Html.TextBox(null, null, new { type="file", @class="input-file" })
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我得到一些例外.怎么了?

Ali*_*hşi 15

模型

public class FeedbackForm
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Company { get; set; }
    public string AdditionalInformation { get; set; }
    public HttpPostedFileBase ProjectInformation { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

视图

@model FeedbackForm

@Html.TextBox("Name")
@Html.TextBox("Email")
...
@Html.TextBox("ProjectInformation", null, new { type="file", @class="input-file" })

// submit button
Run Code Online (Sandbox Code Playgroud)

我推荐的观点(强烈打字)

@model FeedbackForm

@Html.TextBoxFor(model=>model.Name)
@Html.TextBoxFor(model=>model.Email)
...
@Html.TextBoxFor(model=>model.ProjectInformation, null, new { type="file", @class="input-file" })

// submit button
Run Code Online (Sandbox Code Playgroud)

调节器

[HttpPost]
public ActionResult FeedbackForm(FeedbackForm model)
{
    // this is your uploaded file
    var file = model.ProjectInformation;
    ...

    return View();
}
Run Code Online (Sandbox Code Playgroud)

MVC正在使用名称对话,因此如果对您的模型使用相同的文本框变量名称,则mvc会将您的输入绑定到模型.


Jul*_*lla 5

我认为你得到了一个空值,因为你没有在你的表单标签中指定 enctype。

@using (Html.BeginForm("ActionMethodName", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" })) { }

一个有效的例子总是有帮助的。

访问http://www.mindstick.com/Articles/cf1e1dd9-fdba-4617-94f0-407223574447/?Upload%20File%20in%20Asp.Net%20Mvc%204