MVC3 ::在一个动作中传递一个对象和一个HttpPostedFile

And*_*ans 0 file-upload asp.net-mvc-3

我在获取上传文件(HTTPPostedFile)和发布到操作的对象时遇到问题.我有一个名为widget的类:

public class Widget
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FilePath { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在Widget控制器中,我有一个'添加'方法

public ActionResult Add()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

和一个重载的方法来接受用户回发的内容

[HttpPost]
public ActionResult Add(Widget widget, HttpPostedFile file)
{
    // Save posted file using a unique
    // Store the path/unique name in Widget.FilePath
    // Save new Widget object
    return View();
}
Run Code Online (Sandbox Code Playgroud)

在视图中我有以下内容:

@model Project.Models.Widget
@{
    using(Html.BeginForm())
    {
        Html.LabelFor(model => model.FirstName)<br />
        Html.TextBoxFor(model => model.FirstName)<br />
        Html.LabelFor(model => model.LastName)<br />
        Html.TextBoxFor(model => model.LastName)<br />
        <input type="file" id="file" /><br />
        <input type="submit" value="Save" />
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是让用户填写表格并选择要上传的文件.上传文件后,我想使用唯一名称保存文件,然后将文件路径存储为widget.FilePath.

每次我尝试时,都会填充widget对象,但uploadedFile为null.

任何帮助将不胜感激.

Dar*_*rov 6

您的代码存在一些问题.

  • 确保您已enctype="multipart/form-data"为表单设置了正确的内容,否则您将无法上传任何文件.
  • 确保文件输入具有name属性,并且此属性的值与操作参数的名称匹配.分配id对服务器端绑定没有影响.

例如:

@model Project.Models.Widget
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.LabelFor(model => model.FirstName)<br />
    @Html.TextBoxFor(model => model.FirstName)<br />
    @Html.LabelFor(model => model.LastName)<br />
    @Html.TextBoxFor(model => model.LastName)<br />
    <input type="file" id="file" name="file" /><br />
    <input type="submit" value="Save" />
}
Run Code Online (Sandbox Code Playgroud)

还要确保控制器操作适用于HttpPostedFileBase而不是HttpPostedFile:

[HttpPost]
public ActionResult Add(Widget widget, HttpPostedFileBase file)
{
    // Save posted file using a unique
    // Store the path/unique name in Widget.FilePath
    // Save new Widget object
    return View();
}
Run Code Online (Sandbox Code Playgroud)

您还可以将2个参数合并到单个视图模型中:

public class Widget
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FilePath { get; set; }
    public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

[HttpPost]
public ActionResult Add(Widget widget)
{
    // Save posted file using a unique
    // Store the path/unique name in Widget.FilePath
    // Save new Widget object
    return View();
}
Run Code Online (Sandbox Code Playgroud)

最后阅读以下博文:http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx