始终错误对象引用未设置为HttpPostedFileBase集合中对象的实例

时间:2014-12-08 03:34:48

标签: c# asp.net-mvc nullreferenceexception

为什么我使用IEnumerable文件库时会出错?

我使用此代码

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

  <div class="form-horizontal">
    <h4>AlbumViewModel</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Toltip, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Toltip, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Toltip, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Imageurl1, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="Files" value=" " id="File1" />
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Imageurl2, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="Files" value=" " id="File2" />
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Imageurl3, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="Files" value=" " id="File3" />
        </div>
    </div>`

和Controller中的这段代码

[HttpPost]
public ActionResult Create(AlbumViewModel viewModel, IEnumerable<HttpPostedFileBase> files)
{
    var file = files.ToList();
    if (file[1].ContentLength>0)
    {
        viewModel.Imageurl1 = file[1].FileName;
    }
    if (file[2].ContentLength > 0)
    {
        viewModel.Imageurl2 = file[2].FileName;
    }
    if (file[3].ContentLength > 0)
    {
        viewModel.Imageurl3 = file[3].FileName;
    }
    return View();
}

但总是有错误

http://i.stack.imgur.com/Fzvff.png

1 个答案:

答案 0 :(得分:-2)

List<T>的索引从0开始,因此除非列表中有多个文件,否则您将收到空引用异常。

(file[0].ContentLength>0)...