c# - 图像文件名未传递给 Controller ​​ mvc c#

标签 c# jquery asp.net-mvc

当我保存按钮然后将值传递给 Controller ​​时,我在客户端存储了文件名,所以我想要 Controller 中的文件名,但图像文件显示空值。请这里的任何专家告诉我哪里错了以及我的代码中有什么问题。

我还有一个 Controller 代码,你看,请告诉我哪里错了,我的代码有什么问题。

$("#addToList").click(function (e) {
            e.preventDefault();

            var Srno = document.getElementById("detailsTable").rows.length,
                PartyName = $("#PartyName").val(),

                imageFile= $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')

            IsMature = $("#chkNIsMature").is(":checked"),
            detailsTableBody = $("#detailsTable tbody");
            var Qt = '<tr><td>' + Srno + '</td><td>' + PartyName + '</td><td id="imgh">' + imageFile + '</td><td>' + IsMature+ '</td><td> <a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
            detailsTableBody.append(Qt);
            clearItem();
    });

 $("#saveQuotation").click(function (e) {
        e.preventDefault();
        var QuotationArr = [];
        QuotationArr.length = 0;
        $.each($("#detailsTable tbody tr"), function () {

            QuotationArr.push({
                Srno: $(this).find('td:eq(0)').html(),
                PartyName: $(this).find('td:eq(1)').html(),

                imageFile: $(this).find('file').attr('id'),
                IsMature: $(this).find('td:eq(3)').html()
            });
        });

        var data = JSON.stringify({
            Qt_ID: parseInt($("#txtQtID").val()),
            EnteryDate: $("#txtNEnteryDate").val(),
            Purpose: $("#txtNPurpose").val(),
            Quot: QuotationArr,
            AddNew: $("#AddNew").val()
        });

HTML

<div class="row">
 <div class="col-4">

 <input type="file" id="imageFile" name="imageFile" accept="image/jpeg, image/png" onchange="ShowImagePreview(this,document.getElementById('ImagePreview'))" />
</div>
  <div class="col-4" style="margin-left:30%; ">
   <img alt="image" src="~/AppFiles/Images/Default.png" height="50" width="50" style="margin-top:-15%" id="ImagePreview">
  </div>
</div>

模型

  [NotMapped]

        public string imageFile { get;set; }

Controller

#region Quotation Insert
        [HttpPost]
        public ActionResult mQuotationInsert(int Qt_ID, string EnteryDate, string Purpose, Quotation[] Quot, string AddNew)
        {
            string result = "Error! Order Is Not Complete!";
            try
            {
                objQuotation.QuotationInsert(Qt_ID, EnteryDate, Purpose, Quot, AddNew);
                ModelState.Clear();
                result = "Quotation Inserted Successfully!";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                throw;
            }

        }



 public int QuotationInsert(int Qt_ID, string EnteryDate, string Purpose, Quotation[] Quot, string AddNew)
        {
            try
            {
                con.Open();
                tr = con.BeginTransaction();

                if (AddNew == "New")
                {

                    cmd = new SqlCommand("Select Right('00' + Cast(ISNULL(MAX(Qt_ID),0)+1  as varchar(2)) + '', 2) from QuotationMain", con);
                    cmd.Transaction = tr;
                    Qt_ID = Convert.ToInt32(cmd.ExecuteScalar().ToString());

                    cmd = new SqlCommand("Sp_QuotationMainInsert", con);
                }
                else
                    cmd = new SqlCommand("Sp_QuotationMainUpdate", con);

                cmd.Parameters.AddWithValue("@Qt_ID", Qt_ID);
                cmd.Parameters.AddWithValue("@Comp_ID", 1);

                if (EnteryDate != null)
                    cmd.Parameters.AddWithValue("@EnteryDate", EnteryDate);
                else
                    cmd.Parameters.AddWithValue("@EnteryDate", string.Empty);

                cmd.Parameters.AddWithValue("@Username", HttpContext.Current.Session["AgentName"]);
                cmd.Parameters.AddWithValue("@Purpose", Purpose);

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Transaction = tr;
                cmd.ExecuteNonQuery();



                if(Quot !=null)
                {
                    for (int i = 0; i < Quot.Length; i++)
                    {
                        try
                        {

                            String dirPath = "~/AppFiles/Images/";
                            byte[] imgByteArray = Convert.FromBase64String(Quot[i].imageFile);
                            File.WriteAllBytes(dirPath, imgByteArray);

                            //string fileName = Path.GetFileNameWithoutExtension(Quot[i].imageFile.FileName);
                            //string extension = Path.GetExtension(Quot[i].imageFile.FileName);
                            //fileName = fileName + DateTime.Now.ToString("dd/MM/yyyy") + extension;
                            //Quot[i].imagePath = "~/AppFiles/Images/" + fileName;
                            //fileName = Path.Combine(HttpContext.Current.Server.MapPath("~/AppFiles/Images/"), fileName);
                            //Quot[i].imageFile.SaveAs(fileName);


                            if (AddNew == "New")
                            {
                                cmd = new SqlCommand("Select ISNULL(MAX(Qt_Dt_ID), 0) + 1 from QuotationDetail", con);
                                cmd.Transaction = tr;
                                mQt_Det_ID = Convert.ToInt32(cmd.ExecuteScalar());


                                cmd = new SqlCommand("Sp_QuotationDetailInsert", con);
                                cmd.Parameters.AddWithValue("@Qt_Dt_ID", mQt_Det_ID);

                            }

                            else if (AddNew == "Edit")
                            {
                                cmd = new SqlCommand("Sp_QuotationDetailUpdate", con);
                                cmd.Parameters.AddWithValue("@Qt_Dt_ID", Quot[i].Qt_Dt_ID);
                            }

                            cmd.CommandType = CommandType.StoredProcedure;

                                cmd.Parameters.AddWithValue("@Qt_Dt_ID", mQt_Det_ID);
                                cmd.Parameters.AddWithValue("@Qt_ID", Qt_ID);
                                cmd.Parameters.AddWithValue("@SrNo", Quot[i].Srno);

                                cmd.Parameters.AddWithValue("@PartyName", Quot[i].PartyName);
                                cmd.Parameters.AddWithValue("@IsMature", Quot[i].IsMature);

                            if (Quot[i].imagePath != null)
                                //cmd.Parameters.AddWithValue("@Image", fileName);

                            cmd.Transaction = tr;
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception)
                        {

                            throw;
                        }


                    }
                }



                tr.Commit();
                return i;
            }
            catch (SqlException sqlex)
            {
                tr.Rollback();
                throw sqlex;  // read all sql error 
            }
            catch (Exception ex)
            {
                tr.Rollback();
                throw ex; // General execption

            }
            finally
            {
                con.Close();
            }
        }

最佳答案

您尝试在 $.each($("#detailsTable tbody tr") 函数,但它不存在,因为您在 addToList 函数中添加了新的 tr,例如

var Qt = '<tr><td>' + Srno + '</td><td>' + PartyName + '</td><td id="imgh">' + imageFile + '</td><td>' + IsMature+ '</td><td> <a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(Qt);   

将代码从 imageFile: $(this).find('file').attr('id'), 更改为 imageFile: $(this).find('td :eq(2)').html(),

最后你的脚本看起来像。

$.each($("#detailsTable tbody tr"), function () {

            QuotationArr.push({
                Srno: $(this).find('td:eq(0)').html(),
                PartyName: $(this).find('td:eq(1)').html(),

                imageFile: $(this).find('td:eq(2)').html(),
                IsMature: $(this).find('td:eq(3)').html()
            });
        });

关于c# - 图像文件名未传递给 Controller ​​ mvc c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52810286/

相关文章:

c# - 禁用 datagridview 中的复制和粘贴

c# - MVC 4 - 报告服务和存储过程

c# - GTK# + WebKit + Windows

c# - 如何在 ASP.NET Core 中的 DbSet 实例上使用 Find(params object[] keyValues) 方法?

javascript - 为什么第二次迭代集合时第一个元素未定义

javascript - 在 JQuery (Javascript) 中构建内存游戏迷你游戏

c# - 我可以在 URL 引用地址检查中使用什么来了解请求来 self 的域中的何处?

c# - 如何在 Entity Framework 中重命名迁移表?

c# - 在不损失图像质量的情况下在 asp.net 中调整图像大小

javascript - 替换字符串的特定标签