Имя файла изображения не передается в контроллер MVC C # - PullRequest
0 голосов
/ 15 октября 2018

У меня есть хранилище имен файлов на стороне клиента, когда я сохраняю кнопку, затем значение передается контроллеру, поэтому я хочу имя файла в контроллере, но файл изображения показывает нулевое значение.Любой эксперт здесь скажет мне, где я ошибаюсь и в чем проблема в моем коде.

У меня есть общий ресурс и код контроллера, и вы видите, пожалуйста, скажите мне, где я не прав и в чем проблема в моем кодекод.

$("#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; }

Контроллер

#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();
            }
        }

1 Ответ

0 голосов
/ 15 октября 2018

Вы пытаетесь найти file с атрибутом id для вновь добавленной функции tr в $.each($("#detailsTable tbody tr"), но ее не существует, поскольку вы добавили новую функцию tr in addToList, например

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()
            });
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...