图像未发布到控制器

时间:2012-11-25 15:39:20

标签: asp.net-mvc file-upload image-uploading image-upload

  

可能重复:
  MVC. HttpPostedFileBase is always null

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

以下是一些代码:

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

Create.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的工作原理为何),我该如何解决?

1 个答案:

答案 0 :(得分:2)

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

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

请查看following article了解更多详情。