【问题标题】:asp.net Razor Pages Image importasp.net Razor Pages 图片导入
【发布时间】:2020-02-26 09:42:34
【问题描述】:

我在 .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)

问题是,Controller中的File每次都是null。

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

【问题讨论】:

  • 您如何将文件发送到控制器?你能告诉我们吗?
  • @RahulSharma 我正在使用视图模型并且我正在使用 Html.Beginform("Contact", "Home", FormMethod.Post

标签: c# html asp.net asp.net-mvc razor


【解决方案1】:

在您的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" })

【讨论】:

    【解决方案2】:

    正如您在评论中所说,您使用的是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 完全相同

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2021-01-06
      • 2019-06-13
      • 2021-05-07
      • 2020-11-21
      • 2018-03-30
      • 2018-10-16
      • 2019-07-25
      • 2018-06-07
      相关资源
      最近更新 更多