【问题标题】:Pass image & data from view to controller将图像和数据从视图传递到控制器
【发布时间】:2012-11-08 10:07:01
【问题描述】:

我想在单击提交按钮时将图像以及一些数据从视图传递到控制器。 下面是我的代码

我的观点

@using (Html.BeginForm("AccountPhotoPost", "Post", FormMethod.Post, new {enctype = "multipart/form-data", accountId = Model.accountId }))
{
       <text>Post Photo : </text> <input type="file" name="file" id="file" />

       <input type="submit" value="Post Photo" id="saveButton"/>
}

我的控制器操作

 [HttpPost]
 public ActionResult AccountPhotoPost(HttpPostedFileBase file, long accountId)
    {

    }

这里的问题是因为它是 FormMethod.Post ,数据不会从视图传递到控制器,如果我删除它,那么数据会传递但图像不会传递。

如何同时发送?

【问题讨论】:

    标签: asp.net-mvc-3 razor


    【解决方案1】:

    试试这个

    @model SomeModel
    @using (Html.BeginForm("AccountPhotoPost", "Post", FormMethod.Post, new {enctype = "multipart/form-data"}))
    {
           <text>Post Photo : </text> <input type="file" name="file" id="file" />
    
            @Html.HiddenFor(model => model.accountId )
           <input type="submit" value="Post Photo" id="saveButton"/>
    }
    

    在控制器中

    [HttpPost]
     public ActionResult AccountPhotoPost(SomeModel model ,HttpPostedFileBase file)
        {
            var Id = model.accountId;
        }
    

    【讨论】:

      【解决方案2】:

      试试这个

       HttpPostedFileBase hpf = Request.Files["file"] as HttpPostedFileBase;
                      var httpPostedFileBase = Request.Files["file"];
                      if (httpPostedFileBase != null && (hpf != null && httpPostedFileBase.ContentLength > 0))  
                      {
                          var postedFileBase = Request.Files["file"];
                          if (postedFileBase != null)
                          {
                              fileName = postedFileBase.FileName;
                              BinaryReader reader = new BinaryReader(postedFileBase.InputStream);
                              byte[] attachmentBinary = reader.ReadBytes((int)postedFileBase.ContentLength);
                              hcUserReview.AttachmentByteValue = attachmentBinary;
                              hcUserReview.FileName = fileName;
                          }
                      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多