【问题标题】:Image not posted to controller [duplicate]图片未发布到控制器 [重复]
【发布时间】:2012-11-25 15:39:20
【问题描述】:

可能重复:
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; }
  }
}

创建.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>
}

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

【问题讨论】:

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


    【解决方案1】:

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

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

    查看following article 了解更多详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2012-12-18
      • 2021-08-08
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多