【问题标题】:I am getting null value of HttpPostedFileBase when edit form编辑表单时我得到 HttpPostedFileBase 的空值
【发布时间】:2019-04-01 20:36:21
【问题描述】:

如何在编辑表单时在图像视图中显示上传的图像,然后使用输入类型文件将该图像发送到控制器。

我正在尝试如下,但 HttpPostedFileBase 总是返回空值。

我的查看代码是

 @using (Ajax.BeginForm("AddUpdateCategory", "Categories", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", OnComplete = "", OnSuccess = "", OnBegin = "", OnFailure = " }, new { @enctype = "multipart/form-data", id = "CategoryForm", novalidate = "novalidate" }))

{

<div class="file-upload ">
    <button class="file-upload-btn" type="button" onclick="$('.file-upload-input').trigger( 'click' )">Add Image</button>
    <div class="image-upload-wrap">
        <input class="file-upload-input" type='file' name="file" onchange="readURL(this);" accept="image/*" />
        <div class="drag-text">
            <span> Drag and drop a file or select add Image</span>
        </div>
    </div>
    <div class="file-upload-content">
        <img class="file-upload-image" src="@Model.Base64String" alt="your image" />
        @Html.HiddenFor(x=>x.FileName)
        <div class="image-title-wrap">
            <button type="button" onclick="removeUpload()" class="remove-image">Remove <span class="image-title">@Model.FileName</span></button>
        </div>
    </div>


</div>

}

下面是我的控制器代码。

public ActionResult AddUpdateCategory(Category objCategory, HttpPostedFileBase file, FormCollection fc)
    {

        using (HttpClient client = GetHttpClient())
        {
            try
            {
                if (file != null)

                {
                    var filename = Path.GetFileName(file.FileName);
                    string extension = Path.GetExtension(file.FileName);
                    var fileid = Guid.NewGuid().ToString().Replace("-", "") + extension;
                    var path = Path.Combine(Server.MapPath("~/Uploads/Category/"), fileid);

                    file.SaveAs(path);
                    objCategory.ImageURL = fileid;
                }



            }
            catch (Exception ex)
            {

                ModelState.AddModelError(string.Empty, "Error while uploading the files.");

            }

        }
        return Json(new { ModelState }, JsonRequestBehavior.AllowGet);
    }

【问题讨论】:

  • 如果不知道您的表单代码,将很难为您提供帮助。也许您的文件输入的名称不是file?请更新您的问题并提供更多详细信息。
  • 我已经更新了我的帖子,请立即查看。

标签: javascript jquery asp.net-mvc


【解决方案1】:

确保您的表单标签中有 enctype="multipart/form-data" 属性

【讨论】:

  • 而且,确实,您也缺少表格。文件输入需要带有上述enctype 的表单才能正常运行。
  • 我的表单具有文件上传所需的所有属性,而且我的输入字段(文件)与我的控制器操作(参数)具有相同的名称。有没有办法设置输入类型文件值?
  • 您能否向我们展示您的整个 html 代码,其中表单标签是可见的?在您的视图代码中根本没有表单标签。
  • 您可以查看工作示例here
  • 我已添加表格,请立即查看。当我从计算机中选择文件时,我的编码工作正常。但是当我使用 Base46string 编辑表单并在图像视图中显示图像然后更新一个而不选择文件表单计算机时。我假设我将在 httppostedfilebase 中获取查看的图像。
猜你喜欢
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 2016-03-01
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
相关资源
最近更新 更多