编辑表单时,我得到HttpPostedFileBase的空值

时间:2019-03-31 07:22:36

标签: javascript jquery asp.net-mvc

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

我正在尝试如下操作,但是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);
    }

1 个答案:

答案 0 :(得分:0)

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