繁体   English   中英

将图像传递到控制器ASP.NET MVC

[英]Passing Image to Controller ASP.NET MVC

我正在尝试将Image和ImageName从视图发送到控制器。

这是我的控制器的外观:

  [HttpPost]
  public ActionResult Add(BoxAddViewModel image)
  {
      //TODO: Add new box
      return RedirectToAction("Index");
  }

这是模型:

 public class BoxAddViewModel : BaseViewModel
 {
     public int Id { get; set; }
     [Required]
     [DisplayName("Name")]
     public string Name { get; set; }
     [Required]
     [DisplayName("Source")]
     public HttpPostedFileBase Source { get; set; }

 }

最后是视图:

@using (Html.BeginForm("Add", "BoxManagement", new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{

    <div class="form-group">
        @Html.LabelFor(m => m.Name, new { @class = "col-sm-2 control-label" })
        <div class="col-sm-10">
            @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @name = "Name"})
            @Html.ValidationMessageFor(m => m.Name)
        </div>
        @Html.LabelFor(m => m.Source, new { @class = "col-sm-2 control-label" })
        <div class="col-sm-10">
            <!--Html.TextBoxFor(m => m.Source, new { type = "file",}) -->
            @Html.ValidationMessageFor(m => m.Source)
            <input type="file" name="Source" id="Source" />
        </div>
    </div>
    <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span>Add</button>
    @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
}

它进入Add方法,并且Name属性值正确,但是Source为空。

有人知道如何解决吗?

您使用BeginForm()的错误重载并添加路由值,而不是html属性(始终检查生成的html)。 采用

@using (Html.BeginForm("Add", "BoxManagement", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))

旁注:从TextBoxFor()方法中删除new { @name = "Name"} 除非您希望绑定失败,否则不要尝试覆盖由HtmlHelper方法生成的name属性(这种情况下它什么也不做)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM