繁体   English   中英

asp.net Razor Pages 图片导入

[英]asp.net Razor Pages Image import

我在 .cshtml 文件中得到以下代码:

<tr>
   <td class="registerWidth"><b>Image:</b></td>
   <td>
      @Html.TextBoxFor(m => m.File, new { type = "file", accept="image/*" })
      @Html.ValidationMessageFor(m => m.File, "", new { @class = "redColor" })
   </td>
</tr>

这是在我的 ViewModel 中:

  public Image File { get; set; }

(图片来自 System.Drawing)

问题是,每次控制器中的文件都是空的。

 public ActionResult Contact(ContactViewModel data)
        {
            var Image = data.File //data.File is null
        }

在您的ViewModel ,您需要将类型从Image更改为HttpPostedFileBase

public HttpPostedFileBase File { get; set; }

还有你的Controller

[HttpPost]
public ActionResult Contact(ContactViewModel data)
{
   var Image = data.File //data.File is null
}

您的Form应如下所示:

@Html.Beginform("Contact", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })

正如您在评论中所述,您正在使用Html.Beginform("Contact", "Home", FormMethod.Post

但是,当将图像发布到控制器方法时,我是否可以建议以下内容,它似乎工作正常。

 @using ("Contact", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})
 {
     // form things blah blah blag

     // When it comes to inputting the image file, I suggest you do the following
     // Instead of this @Html.TextBoxFor(m => m.File, new { type = "file", accept="image/*" })

    // Have
    <input type="file" name="file" id="fileUpload" accept=".png, .jpg, .jpeg"/>
 }

您的控制器方法将如下以反映这些更改。

public ActionResult Contact(ContactViewModel model, HttpPostedFileBase file)
{
    var Image = file.FileName;
}

那么我们在这里做什么?

我们正在创建一个表单,就像您之前所做的那样,但我们添加了一个额外的参数,用于指定在将表单传递给控制器​​时应如何编码表单。

<input type="file" name="file" id="fileUpload" accept=".png, .jpg, .jpeg"/>

在这里,我们说将有一个名为“文件”的输入,可以接受 png、jpg 或 jpeg 图像。

HttpPostedFileBase file

这是我们将要传递的文件。 name必须与输入标签中的name完全相同

暂无
暂无

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

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