首页 > 解决方案 > 在 Asp.Net MVC 的 HttpPostedFileBase 中获取空值

问题描述

我正在尝试将图像保存在 asp.net mvc 中,但每次传递值时,我都会在 post 方法的控制器中的 httppostedfilebase 参数中获取空值。我该怎么解决这个问题?我已经搜索了答案,但互联网上的答案都没有帮助。我的控制器代码:

 [HttpPost]
    public ActionResult Products(ItemDTO itemDTO,HttpPostedFileBase Picture1)
    {
            itemDTO.OrderItems = null;
        var folder = this.Server.MapPath("~/Images/");
        string newGuid = Guid.NewGuid().ToString();
        string pathToCreate = Path.Combine(folder);
        if (!System.IO.Directory.Exists(pathToCreate))
        {
            System.IO.Directory.CreateDirectory(System.IO.Path.Combine(folder));
        }
        //var fileName = pathToCreate + "//" + System.IO.Path.GetFileName(Picture1File.FileName);
        var imageName = newGuid + System.IO.Path.GetExtension(System.IO.Path.GetFileName(Picture1.FileName));
        var fileName = pathToCreate + imageName;
        Picture1.SaveAs(fileName);

        //itemDTO.imageName = imageName;
        //....and update the database itemDTO
        try
        {
            if (itemDTO.ItemId == 0)
                {
               
                List<ItemDTO> items = new List<ItemDTO>();
                    //Dictionary<string, string> postParams = new Dictionary<string, string>();
                    IRestResponse response = APIHelper.InvokePOSTMethod(Constants.CreateItem, itemDTO);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        items = new JavaScriptSerializer().Deserialize<List<ItemDTO>>(response.Content);
                    }
                    //ViewBag.Error = "Data save successsful!";
                    else
                        ViewBag.Error = response.Content;
                }
                else
                {
                    //List<ItemDTO> item = new List<ItemDTO>();
                    //Dictionary<string, string> dict = new Dictionary<string, string>();
                    //dict.Add("id", itemDTO.ToString());
                    IRestResponse response = APIHelper.InvokePOSTMethod(Constants.UpdateItem, itemDTO);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        List<ItemDTO> item = new List<ItemDTO>();
                        item = new JavaScriptSerializer().Deserialize<List<ItemDTO>>(response.Content);
                    }
                    //ViewBag.Error = "Data save successsful!";
                    else
                        ViewBag.Error = response.Content;
                }
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
                return Json("false", JsonRequestBehavior.AllowGet);

            }
        return Json("true", JsonRequestBehavior.AllowGet);


    }

我的模特班:

 public class ItemDTO
{

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public ItemDTO()
    {
        this.OrderItems = new HashSet<OrderItem>();
    }

    public int ItemId { get; set; }
    public string ItemCategory { get; set; }
    public string ItemName { get; set; }
    public Nullable<decimal> Price { get; set; }

    public string Picture1 { get; set; }
    public string Desctiption { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OrderItem> OrderItems { get; set; }
   
}

我的观点:

<form id="AddProduct" class="needs-validation" novalidate method="post" enctype="multipart/form-data">
        <div class="wrapper">

        
        <div class="main-panel">
        @Html.HiddenFor(x => x.ItemId)
            <div class="content">
                <div class="row" id="frmAddProduct">
                    <div class="info-panel">
                        <div id="form-mode">

                        </div>
                        @*<div id="validation-summary">Please provide values for the highlighted fields.</div>*@
                    </div>
                    <div class="col-md-3">


                        <div class="card">
                            <div class="card-header card-menu py-3">
                                Add Products
                                <div class="headerRightFeatures">
                                    <img src="~/Content/assets/img/delete.png" alt="" id="delete">
                                    </div>
                                </div>
                            <div class="card-body">




                                <div class="form-row">
                                    <div class="col-md-12 mb-3">
                                        <label for="ItemName">Category</label>
                                        @Html.EditorFor(model => model.ItemCategory, new { htmlAttributes = new { @class = "form-control" } })
                                        <div class="invalid-feedback">
                                            Please provide a valid product name.
                                        </div>
                                    </div>
                                </div>

                                <div class="form-row">
                                    <div class="col-md-12 mb-3">
                                        <label for="ItemName">Product Name</label>
                                        @Html.EditorFor(model => model.ItemName, new { htmlAttributes = new { @class = "form-control" } })
                                        <div class="invalid-feedback">
                                            Please provide a valid product name.
                                        </div>
                                    </div>
                                </div>

                                <div class="form-row">
                                    <div class="col-md-12 mb-3">
                                        <label for="Price">Price</label>
                                        @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                                        <div class="invalid-feedback">
                                            Please provide a valid price.
                                        </div>
                                    </div>
                                </div>

                              

                                <div class="form-row">
                                    <div class="col-md-12 mb-3">
                                        @Html.LabelFor(model => model.Picture1)
                                        <input type="file" id="Picture1" name="Picture1" />

                                    </div>
                                </div>

                                <div class="form-row">
                                    <div class="col-md-12 mb-3">
                                        <label for="Price">Description</label>
                                        @Html.EditorFor(model => model.Desctiption, new { htmlAttributes = new { @class = "form-control" } })
                                        <div class="invalid-feedback">
                                            Please provide a valid price.
                                        </div>
                                    </div>
                                </div>

                              



                                <div class="wAuto button-wrapper fleft">
                                    <input type="button" value="Save" class="btn btn-primary btn-sm" id="btn-submit-product" />
                                    <input type="button" value="Cancel" class="btn btn-primary btn-sm" id="btn-cancel-product" />
                                </div>

                            </div>
                            </div>
                    </div>
                </div>




                <table id="productlisting" class="table table-striped table-bordered" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th>Item Id</th>
                            <th>Item Category</th>
                            <th>Item Name</th>

                            <th>Picture1</th>
                            <th>Price</th>
                            <th>Description</th>

                        </tr>
                    </thead>


                </table>

标签: sql-serverasp.net-mvchttppostedfilebase

解决方案


使用提交按钮而不是按钮

利用

<input type="submit" value="Save" class="btn btn-primary btn-sm" id="btn-submit-product" />

代替

<input type="button" value="Save" class="btn btn-primary btn-sm" id="btn-submit-product" />

HttpPostedFileBase 仅在按钮类型为提交时获取值

<form id="AddProduct" class="needs-validation" novalidate method="post" enctype="multipart/form-data">
    <div class="wrapper">
 @Html.Hidden("ItemId", 2)
        <div class="main-panel">
            <div class="content">
                <div class="row" id="frmAddProduct">
                    <div class="info-panel">
                        <div id="form-mode">

                        </div>
                    </div>
                    <div class="col-md-3">

                        <div class="form-row">
                            <div class="col-md-12 mb-3">
                                <input type="file" id="Picture1" name="Picture1" />

                            </div>
                        </div>

                        <div class="wAuto button-wrapper fleft">
                            <input type="submit" value="Save" class="btn btn-primary btn-sm" id="btn-submit-product" />
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</form>



        [HttpPost]
        public ActionResult Index(int ItemId, HttpPostedFileBase Picture1)
        {
            return View();
        }

推荐阅读