c# - mvc ajax表单发布空列表问题

标签 c# jquery ajax asp.net-mvc asp.net-mvc-4

这是我的 View 的 ajax 形式:

@using (Ajax.BeginForm("SendIndoorRequest", "TestRequest", new AjaxOptions { OnBegin = "SendRequestBegin", OnComplete = "SendRequestComplete", OnFailure = "SendRequestFail", OnSuccess = "SendRequestSuccess" }, new { enctype = "multipart/form-data", id = "ImgUpload" }))
{

    <input type="hidden" name="CliqPanelID" value="@ViewBag.OrgID" />
    <input type="hidden" name="TypeOfRequest" value="I" />
    <input type="hidden" name="patient_id" value="@ViewBag.PatientId" />
    <input type="hidden" name="bed_no" value="@ViewBag.PatientBedNo" />
    <input type="hidden" name="ward_no" value="@ViewBag.PatientWardNo" />


    @*<div class="progress">
    <div class="bar"></div >
    <div class="percent">0%</div >
</div>

<div id="status"></div>*@
<div  class="row"  style="margin-top:5px;margin-bottom:5px;">
@*input fields*@

<div class="col-lg-8">
  <div class="col-lg-4">
          <div class="col-lg-12"><label>Request Type:</label></div>
         <div class="col-lg-12">
                 @Html.DropDownList("RequestType", null, "Select Request Type", new { @style = "width:170px;", @id = "ddlRequestType" })    
          </div>
          <div id="ddlRequestTypeValidate" style="margin-left:12px;color:red;display:none;">
          Select Request Type
          </div>
         </div>

         <div class="col-lg-4">
          <div class="col-lg-12"><label>Reffering Doctor:</label></div>
         <div class="col-lg-12">
                 @Html.DropDownList("CliqDoctorID", null, "Select Reffering Doctor", new { @style = "width:180px;", id = "ddlRefDoctors", @class = "chosen-select" })    
          </div>
          <div id="ddlRefDoctorsValidate" style="margin-left:12px;color:red;display:none;">
          Select Reffering Doctor
          </div>
         </div>


         <div class="col-lg-4">
         <div class="col-lg-12"><label>Doctor Name</label>
         </div>
          <div class="col-lg-12">
         @Html.TextBoxFor(o => o.DoctorName, new { placeholder = "In case Doctor not in list" })
         </div> 
         <div id="DoctorNameValidate" style="margin-left:12px;color:red;display:none;">
          Enter Reffering Doctor
          </div> 
         </div>





         @Html.HiddenFor(o => o.BookedTestsIds, new { @id = "bookedTestsIds" })
         @*@Html.HiddenFor(o => o.)*@

          @*<input type="hidden" name="Tests[0].TestId" value="1" />
          <input type="hidden" name="Tests[0].Charges" value="100" />*@


          <div style"clear:both; margin-bottom:5px;"></div>



          <div class="col-lg-4">
          <div class="col-lg-12"><label>Authorization Code:</label></div>
         <div class="col-lg-12">
         @if (Session["AccountType"].ToString() == "panel")
         {
             @Html.TextBoxFor(o => o.AuthCode1, new { @disabled = "disabled" })
             @Html.HiddenFor(o => o.AuthCode1)
         }
         else
         {
                 @Html.TextBoxFor(o => o.AuthCode1)
         }
          </div>
          <div id="AuthCode1Validate" style="margin-left:12px;color:red;display:none;">
          Enter Authorization Code
          </div> 
         </div>

@*<div class="col-lg-4">
          <div class="col-lg-12"><label>Prescription Reference:</label></div>
         <div class="col-lg-12">
              <input type="file" id="uploadFile" name="files"><br>
    <span id="uploadLoader" style="display:none;"><img id="searchLoader" src="@Url.Content("~/Images/loader.gif")" />Uploading Please Wait</span>
          </div>
          <div style="margin-left:12px;color:red;">

          </div>
         </div>*@


         <div class="col-lg-4">
          <div class="col-lg-12"><label>Prescription Reference:</label></div>
         <div class="col-lg-12">
               <div id="uploadControlContainer">
                 <input type="file" name="fileUpload" value="" id="uploadFile" /> 
                 <p><a href="javascript:$('#uploadFile').uploadifyUpload();">Upload Files</a></p>
                 </div>
          </div>
          <input type="hidden" name="FilePath" value="" id="UploadedFile" /> 
          <div style="margin-left:12px;color:red;">

          </div>
         </div>






         <div class="col-lg-3">
         <div class="col-lg-12">&nbsp;
         </div>
          <div class="col-lg-12">
         <input class="btn btn-primary" style="padding: 0 5px; !important;" id="btnSendRequest" type="submit" value="Send Request"/>
         </div>  
         </div>




</div>


@*input fields portion end*@


@*card portion*@
<div class="col-lg-4" style="background:white; border-radius:4px;padding:4px; box-shadow: 2px 2px 2px 2px #888888; width:32.333% !important; margin-left:10px;">
<div class="col-lg-2"  style="padding-left: 4px !important;padding-right: 2px; !important"><img id="PatientPic" src="" style=" width: 100%;" /></div>
<div class="col-lg-10"  style="padding-left: 4px !important;padding-right: 2px; !important">
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Patient:</strong></div>
<div class="col-lg-9" id="EmpName"  style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">@ViewBag.PatientName </div>

<div style="clear:both;"></div>
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Ward/Room:</strong></div>
<div class="col-lg-9" id="DepName"  style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">@ViewBag.PatientWardNo </div>

<div style="clear:both;"></div>
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Bed No:</strong></div>
<div class="col-lg-9" id="Relation"  style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">@ViewBag.PatientBedNo  </div>

</div>

</div>
@*card portion end*@






</div>





<div id="panelTestsContainer">

</div>

    <div id="hiddenContainer">
    <input type="hidden" id="delimCharges" />
    <input type="hidden" id="delimTestId" />
    <input type="hidden" id="delimTestName" />
    </div>

    <div id="BookedTestsContainer">

    </div>

}

在我看来,复选框上有测试名称的复选框已选中或未选中事件,我发送了一个ajax调用来维护服务器端的列表,但如果我只检查1个测试,则发布的列表为空,但当我检查超过1个时然后发布带有正确计数和数据的列表,我没有得到什么问题:

这是我的复选框事件的 jquery 代码:

$("input.checkBoxTests").live('change', function () {


            var TestID = this.id;

            var charges = $('#sample-table-3').find('td.TestCharges#' + TestID).html();
            var TestName = $('#sample-table-3').find('td.TestName#' + TestID).html()

            if (this.checked) {


                var AddUrl = '@Url.Action("AddTest","TestRequest")';



                $.post(AddUrl,
                { TestId: TestID, Charges: charges, TestName: TestName },
                 function (response) {

                     $("div#BookedTestsContainer").html(response);

                 });


                $("#selectedTestsTable").find('tbody')
    .append($('<tr>')
    .attr('id', TestID)
    .attr('class', "bookedTest")
        .append($('<td>')
            .append($('#sample-table-3').find('td.TestName#' + TestID).html()

            )
        )
    );





            }

            else {


                var RemoveUrl = '@Url.Action("RemoveTest","TestRequest")';

                $.post(RemoveUrl,
                { TestId: TestID, Charges: charges, TestName: TestName },
                 function (response) {

                     $("div#BookedTestsContainer").html(response);

                 });

                $("#selectedTestsTable").find('tr#' + TestID).remove()




            }



        });

这是选中复选框时我的 ajax 调用服务器事件:

[HttpPost]
        public ActionResult AddTest(int TestId,long Charges, string TestName)
        {
            List<Test> bookedTests = new List<Test>();

            if (Session["BookedTests"] != null)
            {
                bookedTests = (List<Test>)Session["BookedTests"];
            }

            Test objTest = new Test();

            objTest.TestId = TestId;
            objTest.Charges = Charges;
            objTest.TestName = TestName;

            bookedTests.Add(objTest);

            Session["BookedTests"] = bookedTests;

            return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml",bookedTests);
        }

这是未选中复选框时我的 ajax 调用服务器端事件:

[HttpPost]
        public ActionResult RemoveTest(int TestId)
        {

            List<Test> bookedTests = new List<Test>();

            if (Session["BookedTests"] != null)
            {
                bookedTests = (List<Test>)Session["BookedTests"];

                bookedTests.RemoveAll(key => key.TestId == TestId);

                Session["BookedTests"] = bookedTests;

                return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml", bookedTests);
            }

            else
            {
                return new EmptyResult();
            }


        }

这是我的表单发布方法:

[HttpPost]
        public string SendIndoorRequest(TestRequestViewModel form, IEnumerable<HttpPostedFileBase> files)
        {

            using (var db = new cloud_clinicEntities())
            using (var scope = new TransactionScope())
            {
                org_requestm objRequestM = new org_requestm();

                objRequestM.authcode1 = form.AuthCode1;
                objRequestM.admission_no = form.admission_no;
                objRequestM.bed_no = form.bed_no;
                objRequestM.ward_no = form.ward_no;
                objRequestM.patient_id = form.patient_id;
                objRequestM.RequestType = form.TypeOfRequest;
                if (form.DependentId == 0)
                {
                    objRequestM.cliq_dependent_id = null;
                }
                else
                {
                    objRequestM.cliq_dependent_id = form.DependentId;
                }
                if (form.CliqDoctorID != 0)
                {
                    objRequestM.cliq_doctor_id = form.CliqDoctorID;
                }
                if (!string.IsNullOrEmpty(form.DoctorName))
                {
                    objRequestM.doctor_name = form.DoctorName;
                }

                objRequestM.request_total_amount = 0;

                for (int i = 0; i < form.BookedTests.Count; i++)
                {
                    if (form.BookedTests[i].Charges != 0)
                    {
                        objRequestM.request_total_amount = objRequestM.request_total_amount + form.BookedTests[i].Charges;
                    }
                }


                objRequestM.cliq_panel_id = form.CliqPanelID;

                if (Session["AccountType"].ToString() == "lab")
                {
                    objRequestM.enteredby_clinicPersonId = int.Parse(Session["userId"].ToString());
                }
                else
                {
                    objRequestM.enteredby_orgPersonId = int.Parse(Session["userId"].ToString());
                }
                objRequestM.enteredon = DateTime.Now;

                objRequestM.org_request_type_id = form.RequestType;

                if (Request.Files != null)
                {
                    foreach (string requestFile in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[requestFile];
                        if (file.ContentLength > 0)
                        {
                            string fileName = Path.GetFileName(file.FileName);
                            string directory = Server.MapPath("~/uploads/");

                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }
                            string path = Path.Combine(directory, fileName);

                            file.SaveAs(path);

                            objRequestM.perscription_doc_path = "~/Uploads/" + file.FileName;
                        }
                    }
                }

                db.org_requestm.Add(objRequestM);

                db.SaveChanges();


                long RequestmId = db.org_requestm.Max(o => o.id);

                for (int i = 0; i < form.BookedTests.Count; i++)
                {
                    if (form.BookedTests[i].TestId != 0)
                    {
                        org_requestd objRequestd = new org_requestd();

                        objRequestd.amount = form.BookedTests[i].Charges;
                        objRequestd.lims_test_id = form.BookedTests[i].TestId;
                        objRequestd.lims_test_name = form.BookedTests[i].TestName;
                        objRequestd.Status = "P";
                        objRequestd.requestm_id = RequestmId;


                        db.org_requestd.Add(objRequestd);

                        try
                        {
                            db.SaveChanges();
                        }
                        catch (System.Data.Entity.Validation.DbEntityValidationException e)
                        {
                            var outputLines = new List<string>();
                            foreach (var eve in e.EntityValidationErrors)
                            {
                                outputLines.Add(string.Format(
                                    "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                                    DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                                foreach (var ve in eve.ValidationErrors)
                                {
                                    outputLines.Add(string.Format(
                                        "- Property: \"{0}\", Error: \"{1}\"",
                                        ve.PropertyName, ve.ErrorMessage));
                                }
                            }
                            System.IO.File.AppendAllLines(@"d:\EFerrors.txt", outputLines);
                        }
                    }

                }


                scope.Complete();


                Session.Remove("BookedTests");

                return "success";
            }
        }

这是我的复选框事件:

$("input.checkBoxTests").live('change', function () {


            var TestID = this.id;

            var charges = $('#sample-table-3').find('td.TestCharges#' + TestID).html();
            var TestName = $('#sample-table-3').find('td.TestName#' + TestID).html()

            if (this.checked) {


                var AddUrl = '@Url.Action("AddTest","TestRequest")';

                //AddUrl = AddUrl + "?TestId=" + TestID + "&Charges=" + charges + "&TestName=" + TestName;

                $.post(AddUrl,
                { TestId: TestID, Charges: charges, TestName: TestName },
                 function (response) {

                     $("div#BookedTestsContainer").html(response);

                 });


                $("#selectedTestsTable").find('tbody')
    .append($('<tr>')
    .attr('id', TestID)
    .attr('class', "bookedTest")
        .append($('<td>')
            .append($('#sample-table-3').find('td.TestName#' + TestID).html()

            )
        )
    );

                /*var TestIdIndex = $("input.iHiddenTestId").length;

                var Mytest = $('input.MyTest').length;

                alert('my' + Mytest);

                $('form#ImgUpload input.iHiddenTestId').each(function (i) {
                // do something
                alert($(this).val());
                });



                var newTestId = $("<input id='" + this.id + "' type='hidden' value='" + this.id + "' class='iHiddenTestId' name='Tests[" + TestIdIndex + "].TestId' />");
                $("form#ImgUpload").append(newTestId);

                var Testing = $("<input id='" + this.id + "' type='hidden' value='" + this.id + "' class='MyTest' name='Tests[" + TestIdIndex + "].TestId' />");
                $("form#ImgUpload").append(Testing);

                var ChargesIndex = $("form#ImgUpload input.iHiddenCharges").length;


                var newCharges = $("<input id='" + this.id + "' type='hidden' value='" + charges + "' class='iHiddenCharges' name='Tests[" + ChargesIndex + "].Charges' />");
                $("form#ImgUpload").append(newCharges);

                var TestNameIndex = $("form#ImgUpload input.iHiddenTestName").length;




                var newTestName = $("<input id='" + this.id + "' type='hidden' value='" + TestName + "' class='iHiddenTestName' name='Tests[" + TestNameIndex + "].TestName' />");
                $("form#ImgUpload").append(newTestName);*/



            }

            else {


                var RemoveUrl = '@Url.Action("RemoveTest","TestRequest")';

                $.post(RemoveUrl,
                { TestId: TestID, Charges: charges, TestName: TestName },
                 function (response) {

                     $("div#BookedTestsContainer").html(response);

                 });

                $("#selectedTestsTable").find('tr#' + TestID).remove()




            }



        });

最佳答案

搞砸后我做了什么,在添加测试上创建列表时,我在列表的索引 0 上添加了一个虚拟的空条目,并在保存到数据库时检索时,我跳过了列表的第 0 个索引,这是代码:

 [HttpPost]
        public ActionResult AddTest(int TestId,long Charges, string TestName)
        {
            List<Test> bookedTests = new List<Test>();

            if (Session["BookedTests"] != null)
            {
                bookedTests = (List<Test>)Session["BookedTests"];
            }

            else
            {

                Test dummyTest = new Test();

                dummyTest.TestId = 0;
                dummyTest.Charges = 0;
                dummyTest.TestName = "dummy";

                bookedTests.Add(dummyTest);

            }

            Test objTest = new Test();

            objTest.TestId = TestId;
            objTest.Charges = Charges;
            objTest.TestName = TestName;

            bookedTests.Add(objTest);

            Session["BookedTests"] = bookedTests;

            return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml",bookedTests);
        }

这是我跳过列表第一项的保存:

[HttpPost]
        public string SendIndoorRequest(TestRequestViewModel form, IEnumerable<HttpPostedFileBase> files)
        {

            using (var db = new cloud_clinicEntities())
            using (var scope = new TransactionScope())
            {
                org_requestm objRequestM = new org_requestm();

                objRequestM.authcode1 = form.AuthCode1;
                objRequestM.admission_no = form.admission_no;
                objRequestM.bed_no = form.bed_no;
                objRequestM.ward_no = form.ward_no;
                objRequestM.patient_id = form.patient_id;
                objRequestM.RequestType = form.TypeOfRequest;
                if (form.DependentId == 0)
                {
                    objRequestM.cliq_dependent_id = null;
                }
                else
                {
                    objRequestM.cliq_dependent_id = form.DependentId;
                }
                if (form.CliqDoctorID != 0)
                {
                    objRequestM.cliq_doctor_id = form.CliqDoctorID;
                }
                if (!string.IsNullOrEmpty(form.DoctorName))
                {
                    objRequestM.doctor_name = form.DoctorName;
                }

                objRequestM.request_total_amount = 0;

                for (int i = 0; i < form.BookedTests.Count; i++)
                {
                    if (form.BookedTests[i].Charges != 0)
                    {
                        objRequestM.request_total_amount = objRequestM.request_total_amount + form.BookedTests[i].Charges;
                    }
                }


                objRequestM.cliq_panel_id = form.CliqPanelID;

                if (Session["AccountType"].ToString() == "lab")
                {
                    objRequestM.enteredby_clinicPersonId = int.Parse(Session["userId"].ToString());
                }
                else
                {
                    objRequestM.enteredby_orgPersonId = int.Parse(Session["userId"].ToString());
                }
                objRequestM.enteredon = DateTime.Now;

                objRequestM.org_request_type_id = form.RequestType;

                if (Request.Files != null)
                {
                    foreach (string requestFile in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[requestFile];
                        if (file.ContentLength > 0)
                        {
                            string fileName = Path.GetFileName(file.FileName);
                            string directory = Server.MapPath("~/uploads/");

                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }
                            string path = Path.Combine(directory, fileName);

                            file.SaveAs(path);

                            objRequestM.perscription_doc_path = "~/Uploads/" + file.FileName;
                        }
                    }
                }

                db.org_requestm.Add(objRequestM);

                db.SaveChanges();


                long RequestmId = db.org_requestm.Max(o => o.id);

                for (int i = 0; i < form.BookedTests.Count; i++)
                {

                        if (form.BookedTests[i].TestId != 0)
                        {
                            org_requestd objRequestd = new org_requestd();

                            objRequestd.amount = form.BookedTests[i].Charges;
                            objRequestd.lims_test_id = form.BookedTests[i].TestId;
                            objRequestd.lims_test_name = form.BookedTests[i].TestName;
                            objRequestd.Status = "P";
                            objRequestd.requestm_id = RequestmId;


                            db.org_requestd.Add(objRequestd);

                            try
                            {
                                db.SaveChanges();
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException e)
                            {
                                var outputLines = new List<string>();
                                foreach (var eve in e.EntityValidationErrors)
                                {
                                    outputLines.Add(string.Format(
                                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                                        DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                                    foreach (var ve in eve.ValidationErrors)
                                    {
                                        outputLines.Add(string.Format(
                                            "- Property: \"{0}\", Error: \"{1}\"",
                                            ve.PropertyName, ve.ErrorMessage));
                                    }
                                }
                                System.IO.File.AppendAllLines(@"d:\EFerrors.txt", outputLines);
                            }
                        }

                }


                scope.Complete();


                Session.Remove("BookedTests");

                return "success";
            }
        }

关于c# - mvc ajax表单发布空列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21773629/

相关文章:

jquery - 如何创建像 pinterest/snatchly 这样可以抓取图像的书签

ajax - 如何在 AJAX 请求后填充 v-data-table 以在 Laravel 中使用 Vuetify 获取数据?

c# - WCF 服务中的 System.DirectoryServices.AccountManagement.PrincipalContext 和模拟

c# - Directory.GetFiles 上的 LINQ,使用多个排序条件进行过滤和排序

c# - 使用 CodeDom 生成具有值和名称的枚举

ajax - Zend_Form ajax 查询的 csrf 验证

jquery - 同一域上的ajax跨域错误?

c# - 在 iOS 中通过 VPS 访问远程数据

Jquery:不支持drop事件?

javascript - PHP AJAX - &lt;input&gt; 元素可以像 <form> 一样具有 "action"吗?