0

可能重复:
MVC。HttpPostedFileBase 始终为空

我希望用户能够上传图像并将其存储在服务器上以供以后参考。

这是一些代码:

SliderController.cs:

public ActionResult Create()
{
  return View(new SliderImageViewModel());
}

[HttpPost]
public ActionResult Create(SliderImageViewModel sliderImage)
{
  if (ModelState.IsValid)
  {
    var slider = new SliderImage();
    var lastSortOrder =
      Context.SliderImages.Select(p => p.SortOrder).DefaultIfEmpty(0).Max();
    slider.SortOrder = lastSortOrder + 1;

    //TODO: upload image to server and get physical path (GUID)
    //slider.ImageUrl = physical path

    Context.SliderImages.Add(slider);
    Context.SaveChanges();
    return RedirectToIndex();
  }
  else
    return View(sliderImage);
}


public class SliderImageViewModel
{
  [RequiredValue]
  public HttpPostedFileBase Image { get; set; }
  private string _Content;
  public string Content
  {
    get
    {
      if (string.IsNullOrWhiteSpace(_Content))
        return null;
      else
        return _Content;
    }
    set { _Content = value; }
  }
}

创建.cshtml:

@using (Html.BeginForm("Create", "Slider", FormMethod.Post))
{
  @Html.ValidationSummary(true)

  <fieldset>
    <legend>Page</legend>

    <div class="editor-label">
      @Html.Label("Content")
    </div>
    <div class="editor-field">
      @Html.TextBox("content")
    </div>

    <div class="editor-label">
      @Html.Label("Image")
    </div>
    <div class="editor-field">
      @Html.TextBox("image", null, new { type = "file", accept = "image/*" })
    </div>

    <p>
      <input type="submit" value="Save" />
    </p>

  </fieldset>
}

当我提交表单时,参数中的Image属性sliderImage为空(Content有效),我应该如何解决这个问题?

4

1 回答 1

2

如果您希望能够上传文件,则需要在表单上设置enctype属性:multipart/form-data

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

查看following article更多详细信息。

于 2012-11-25T15:40:32.680 回答