图像传递给控制器​​ASP.NET MVC [英] Passing Image to Controller ASP.NET MVC

查看:87
本文介绍了图像传递给控制器​​ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从查看发送图像和ImageName到控制器。

I am trying to send Image and ImageName from View to Controller.

下面是我的控制器的外观:

Here's how my controller looks:

  [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属性值是正确的,但来源为null。

It comes into the Add method and the Name property value is correct but the Source is null.

任何人知道如何解决这个问题?

Anyone know how to solve this?

推荐答案

您使用 BeginForm的)错误的过载(并添加路由值,而不是HTML属性(总是检查在HTML你生成)。使用

Your using the wrong overload of BeginForm() and adding route values, not html attributes (always inspect the html your generating). Use

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

边注:删除新{@name =姓名} TextBoxFor()方法。不要试图重写名称除非你想绑定失败(并通过的HtmlHelper 方法生成的属性是这样的情况下,什么都不做反正)

Side note: Remove new { @name = "Name"} from your TextBoxFor() method. Never attempt to override the name attribute generated by the HtmlHelper methods unless you want binding to fail (and is this case it does nothing anyway)

这篇关于图像传递给控制器​​ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆