mvc ajax form post null list issue - c#

Here is my ajax form of my view:
#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>Upload Files</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">
</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>
}
on my view there are checkboxes with test name on check box checked or unchecked event i sent an ajax call to maintain list on server side but if i only i check 1 test the list posted is null but when i check more than 1 then list is posted with right count and data, whats the issue i am not getting:
Here is my jquery code for checkbox event:
$("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()
}
});
here is my ajax call server event when checkbox is checked:
[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);
}
here is my ajax call server side event when checkbox is unchecked:
[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();
}
}
Here is my form post method:
[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";
}
}
here is my checkbox event:
$("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()
}
});

What i did after messing up with it that on list creating on Add Test i added a dummy empty entry on index 0 of the list and on retrieving while saving in db i am skipping the 0th index of the list, here is the code:
[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);
}
and here is the Saving in which i am skipping the first item of list:
[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";
}
}

Related

Problem with my Jquery function dosent call controllerside method

I have these codes in my Razor which already was working but now it doesn't works:
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Pcode" class="control-label"></label>
<input asp-for="Pcode" class="form-control" id="UserCode" name="UserCode" onchange="UserCheck()" style="background-color:lightyellow" />
<span asp-validation-for="Pcode" class="text-danger"></span>
</div>
<div class="row">
<label class="col-sm-2"></label>
<div class="col-sm-10">
<p id="Status" name="Status" />
</div>
</div>
these are my code in jquery function :
$.noConflict();
function UserCheck()
{
$("#Status").html("Checking ...");
$.post("#Url.Action("CheckIfUserCodeExist", "Leave")",
{
UserCode: $("#UserCode").val(),
},
function (data) {
if (data) {
$("#Status").html(data);
#*$("#Status").html('#TempData["NF"]');*#
$("#UserCode").css("border-color", "Green");
}
else {
$("#Status").html('<font color="Red">این شخص قبلا ثبت نام نشده </font>');
$("#UserCode").css("border-color", "Red");
}
});
}
and here are my code in controller side:
public JsonResult CheckIfUserCodeExist(Int32 UserCode)
{
System.Threading.Thread.Sleep(200);
var SearchData = db.Persons.Where(x => x.Pcode == UserCode).SingleOrDefault();
TempData.Remove("NF");
//TempData.clear();
if (SearchData != null)
{
string N = SearchData.Name;
string F = SearchData.Family;
TempData["code"] = UserCode;
var NF = N + " " + F;
//TempData["NF"] = NF;
return Json(NF);
}
else
{
TempData["code"] = 0;
return Json("");
}
}
would you please help me where is the problem? I tested this several time without error.but now ....

System.Data.Entity.Core.Entity Command Execution Exception

The following unhandled user exception is showing when fetching a list.
System.Data.Entity.Core.EntityCommandExecutionException: 'The data reader is incompatible with the specified 'EE_PlacementCellModel.PlacedCandidateList'. A member of the type, 'DriveDate', does not have a corresponding column in the data reader with the same name.'
The exception is shown in the last return code:
Placement.Context.cs
public virtual ObjectResult<PlacedCandidateList> PlacedCandidateList(Nullable<int> mstID, Nullable<int> cmpID)
{
var mstIDParameter = mstID.HasValue ?
new ObjectParameter("MstID", mstID) :
new ObjectParameter("MstID", typeof(int));
var cmpIDParameter = cmpID.HasValue ?
new ObjectParameter("CmpID", cmpID) :
new ObjectParameter("CmpID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<PlacedCandidateList>("PlacedCandidateList", mstIDParameter, cmpIDParameter);
}
Other related codes are given below:
ReportController.cs
public ActionResult PlacedCandidateList(string MstID, string CmpID)
{
int driveID = 0;
int companyID = 0;
if (MstID != "")
driveID = Convert.ToInt32(MstID);
if (CmpID != "")
companyID = Convert.ToInt32(CmpID);
ViewBag.Status = Db.Status.ToList();
var List = Db.PlacedCandidateList(driveID, companyID);
return Json(List.ToList(), JsonRequestBehavior.AllowGet);
}
public ActionResult PlacedCandidate()
{
ViewBag.Drive = Db.DriveMasters.Where(a => a.Isdeleted == false).ToList();
ViewBag.Company = Db.Companies.Where(a => a.Isdeleted == false).ToList();
return View();
}
[HttpPost]
public ActionResult PlacedCandidate(CandidateList candidate)
{
ViewBag.Drive = Db.DriveMasters.Where(a => a.Isdeleted == false).ToList();
ViewBag.Company = Db.Companies.Where(a => a.Isdeleted == false).ToList();
if (candidate.CompanyID == null)
candidate.CompanyID = 0;
if (candidate.DriveMasterID == null)
candidate.DriveMasterID=0;
List<PlacedCandidateList> CSL = new List<PlacedCandidateList>();
CSL = Db.PlacedCandidateList(candidate.DriveMasterID, candidate.CompanyID).ToList();
WebGrid grid = new WebGrid(source: CSL, canPage: false, canSort: false);
string gridhtml = grid.GetHtml(
columns: grid.Columns(
grid.Column("SerailNo", "Serail No"),
grid.Column("StudentName", "Student Name"),
grid.Column("DriveName", "Drive Name"),
//grid.Column("DriveDate", "Drive Date"),
grid.Column("CompanyName", "Company Name"),
grid.Column("PositionName", "Position Name")
)).ToString();
string exportdata = string.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table {border-collapse: collapse; width: 100%; border: 1px solid #ddd;} th, td {text-align: left;padding: 8px; width:100px; border-bottom: 1px solid #ddd;} tr:nth-child(even){background-color: #f2f2f2} th {background-color: #4CAF50; color: white;} </style>", gridhtml);
var bytes = System.Text.Encoding.UTF8.GetBytes(exportdata);
using (var input = new MemoryStream(bytes))
{
var output = new MemoryStream();
var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
var writer = PdfWriter.GetInstance(document, output);
writer.CloseStream = false;
document.Open();
var xmlworker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
xmlworker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
document.AddTitle("Placed Candidates");
document.AddCreationDate();
document.Close();
output.Position = 0;
return new FileStreamResult(output, "application/pdf");
}
}
PlacedCandidateList.cs
/------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PlacementCell.Models
{
using System;
public partial class PlacedCandidateList
{
public Nullable<long> SerailNo { get; set; }
public int CandidatesListID { get; set; }
public string CompanyName { get; set; }
public string PositionName { get; set; }
public string StudentName { get; set; }
public string DriveName { get; set; }
public string Status { get; set; }
public int StatusID { get; set; }
public string DriveDate { get; set; }
}
}
PlacedCandidate.cshtml
#model PlacementCell.Models.CandidateList
#{
ViewBag.Title = "Placed Candidate";
}
#using (Html.BeginForm("PlacedCandidate", "Report", FormMethod.Post, new { enctype = "multipart/form-data", name = "candidate", id = "candidate" }))
{
<div class="callout bg-gray-light">
<div class="row">
<div class="col-xs-2 col-md-1"><div class="btn btn-app btn-twitter"><i class="glyphicon glyphicon-print"></i>Print</div></div>
</div>
</div>
<section class="content-header">
<h1>
Placed Candidates
<small>Report</small>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-list-alt"></i> Report</li>
<li class="active"><i class="fa fa-circle-o"></i> Placed Candidates</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="box">
<div class="box-body">
<br />
<div class="row">
<div class="col-xs-12 col-md-6">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6"> Placement Drive</div>
<div class="col-md-6">
#Html.DropDownListFor(model => model.DriveMasterID, new SelectList(ViewBag.Drive, "DriveMasterID", "DriveName"), "Select Drive", new { #class = "form-control", #Onchange = " GetVariables();" })
</div>
</div>
<div class="form-group">
<div class="col-md-6">Company</div>
<div class="col-md-6">
#Html.DropDownListFor(model => model.CompanyID, new SelectList(ViewBag.Company, "CompanyID", "CompanyName"), "Select Company", new { #class = "form-control", #Onchange = " GetVariables();" })
</div>
</div>
<div class="form-group">
<div class="col-md-6"></div>
<div class="col-md-6">
Find
</div>
</div>
</div>
</div>
</div>
<div class="row">
<table class="table table-bordered table-hover dataTable">
<thead>
<tr>
<th>
<input type="checkbox" class="checkbox" />All
</th>
<th>
Sl.
</th>
<th>
Company Name
</th>
<th>
Drive Name
</th>
<th>
Drive Date
</th>
<th>
Position Name
</th>
<th>
Student Name
</th>
<th>
</th>
</tr>
</thead>
<tbody id="drive">
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
}
#section scripts
{
<script type="text/javascript">
function GetList() {
var MstID = document.getElementById("DriveMasterID").value;
var CmpID = document.getElementById("CompanyID").value;
//alert(MstID);
$.ajax({
url: '/Report/PlacedCandidateList',
type: "GET",
data: { MstID: MstID, CmpID: CmpID },
dataType: "JSON",
success: function (List) {
//alert("ffffg");
$("#drive").html(""); // clear before appending new list
//alert("ff");
var k = 10;
var j = 1;
$.each(List, function (i, vari) {
var Qun = "arr" + k;
var ErrorQun = "arre" + k;
var chbbx = '<tr id="checkboxes"><td><input type="checkbox" name="CandidatesListID" id=' + k + ' class="checkbox" value=" ' + vari.CandidatesListID + '" checked="checked" disabled="disabled" /></td><td> ' + j + ' </td><td> ' + vari.CompanyName + ' </td><td> ' + vari.DriveName + ' </td><td> ' + vari.DriveDate + '</td><td> ' + vari.PositionName + ' </td><td> ' + vari.StudentName + ' </td><td> ' + vari.Status + '</td></tr>';
$("#drive").append(
$(chbbx));
k++;
j++;
//alert(place.Place1);
}
);
},
error: function (List) {
alert("No Data Found");
$("#drive").html("");
}
});
}
</script>
}

How to insert json message in modal with asp.net mvc

I'm developing a system in .NET and I need to send a json controller msg to the view and show it in modal.
The user will import a spreadsheet and the spreadsheet will be inserted in the database, at the end of the modal it should appear with the message whether it was sent or not.
Or backend is already working.
 
I need help on the front because when I import, it loads a new page with
["Sent with success"]
(the messages are in portuguese) = ["Enviado com sucesso"]
Follows the controller code.
public JsonResult UploadExcel(HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = "C:/Users/70561/Documents";
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var adapter = new OleDbDataAdapter("SELECT * FROM [Planilha1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Planilha1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var dados = from a in excelFile.Worksheet<RETORNO_CM>(sheetName) select a;
foreach (var a in dados)
{
try
{
if (a.CM_CODIGO != null && a.CM_QM_COMPONENTE_RMA != null && a.CM_NS != null && a.CM_DESCRICAO != null &&
a.CM_DEFEITO != null && a.J_FALHA != null &&
a.CM_TIPO_DEFEITO != null && a.J_PLACA_RETRABALHO != null &&
a.J_PLACA_RESTESTADA != null && a.J_STATUS != null && a.CM_NOME_TESTE != null && a.CM_NOME_DEBUG != null)
{
RETORNO_CM CM = new RETORNO_CM();
CM.CM_CODIGO = a.CM_CODIGO;
CM.CM_QM_COMPONENTE_RMA = a.CM_QM_COMPONENTE_RMA;
CM.CM_NS = a.CM_NS;
CM.CM_DESCRICAO = a.CM_DESCRICAO;
CM.CM_DATA_REPARO = a.CM_DATA_REPARO;
CM.CM_DEFEITO = a.CM_DEFEITO;
CM.J_FALHA = a.J_FALHA;
CM.CM_TIPO_DEFEITO = a.CM_TIPO_DEFEITO;
CM.CM_COMPONENTE = a.CM_COMPONENTE;
CM.J_PLACA_RETRABALHO = a.J_PLACA_RETRABALHO;
CM.J_PLACA_RESTESTADA = a.J_PLACA_RESTESTADA;
CM.J_STATUS = a.J_STATUS;
CM.CM_NOME_TESTE = a.CM_NOME_TESTE;
CM.CM_NOME_DEBUG = a.CM_NOME_DEBUG;
db.RETORNO_CM.Add(CM);
db.SaveChanges();
}
else
{
data.Add("<ul>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
//deleting excel file from folder
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
data.Add("Enviado com sucesso");
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
//alert message for invalid file format
data.Add("Apenas arquivos excel sao suportados");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
if (FileUpload == null) data.Add("Selecione um arquivo");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
my view code
<div class="box">
<div class="box-body">
<hr />
<article class="table-responsive" style="overflow:hidden">
<p class="lead">Teste de importação.</p>
<hr />
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return myFunction()" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enviar" id="btnSubmit" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>
<b>Message:</b><br>
<input class="message-edit-text" type="text" size="20">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</article>
</div>
You should not return JSON, as you are performing a full page postback. Instead, you should return a View.
If you do not want to perform a full page postback, you want to use Ajax since the beginning of the request.
For example,
View
Please make sure button is type="button" to avoid full page postback.
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" id="btnSubmit" class="btn btn-primary">
Enviar
</button>
</div>
</div>
</div>
}
<script>
$(function () {
$('#btnSubmit').click(function() {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '#Url.Action("UploadExcel", "RetornoCM")',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function(result) {
alert(result);
},
error: function(err) {
alert(err.statusText);
}
});
}
});
});
</script>
Action Method
[HttpPost]
public ActionResult UploadExcel()
{
if (Request.Files.Count > 0)
{
try
{
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
// Do somethig with file
}
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Source: File Upload Through JQuery AJAX In ASP.NET MVC

How to stop Mvc and MvC web api function from Executing twice in slow internet connection

I have same function in both web api and Mvc Asp.Net project that send message . In web api I use ajax call to make request which is fine on good internet connection but when the internet is slow the function will send the message twice, sometimes three times. I have also try the same with normal Mvc project and still get the same result. I don't know why my function can't send the message once. I have been trying to sort this out now for three days but don't know why it keeping sending multiple times. Any help will be so much appreciated. below is function for webapi.
[Route("Vend")]
[HttpPost]
public HttpResponseMessage Vend()
{
PayVendorModel model = new PayVendorModel();
var rsp = new object();
List<string> error = new List<string>();
if (Request.Content.IsFormData())
{
var provider = Request.Content.ReadAsFormDataAsync();
model = (PayVendorModel)(ModelBinders.BindModel(provider.Result, new PayVendorModel()));
UserProfile userProfile = Permissions.CurrentUser();
bool isVtuSuccess = false;
string vtuReference = string.Empty;
AirVendResponse vend = RequestManager.GetAirVendForUser(Convert.ToInt32(model.Network), model.PhoneNumber, model.Amount, userProfile.VtUUsername, userProfile.PinCode).Result;
if (vend.VendResponse.ResponseCode == "0")
{
isVtuSuccess = true;
vtuReference = model.PhoneNumber;
CashActivity cashAct = new CashActivity()
{
IsVtuSuccess = isVtuSuccess,
Network = StringUtil.CheckNetwork(Convert.ToInt32(model.Network)),
PhoneNumber = vend.VendResponse.Msisdn,
RecordState = new RecordState(new Guid(userProfile.Id)),
Amount = Convert.ToDecimal(vend.VendResponse.Amount),
AVRef = vend.VendResponse.AVRef,
SellRef = vend.VendResponse.Ref
};
CashProvider.Add(cashAct);
rsp = new
{
message = "Succeeded",
};
return Request.CreateResponse(HttpStatusCode.OK, rsp);
}
else
{
rsp = new
{
message = "Error Code: " + vend.VendResponse.ResponseCode + "\n Message: " + vend.VendResponse.ResponseMessage,
};
return Request.CreateResponse(HttpStatusCode.OK, rsp);
}
}
else
{
error.Add("Error Creating Store.");
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelHelper.GetStringError(error));
}
}
Ajax
$("#VendSaveBtn").unbind().bind("click", "#VendSaveBtn", function (e) {
(e.preventDefault) ? e.preventDefault() : e.returnValue = false;
if (!ValidateVend())
CreateVend();
});
function CreateVend() {
$.ajax({
type: 'POST',
timeout: GetTimeOut(),
url: storeUrl + 'Vendor/Vend',
data: $("#UserVendForm").serialize(),
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', GetTokenHeader());
},
success: function (result) {
if(result.message =="Succeeded")
changepage('#nav-panel');
else
createPopup(result.message)
},
error: function (req, s, t) {
hideLoading();
if (req.status == 401) {
RemoveAccess();
changepage("#LoginPage");
}
if (s === "timeout") {
createPopup("Alert:", "Oops! check your internet connection.")
} else if (req.status == 0) {
createPopup("Alert:", internetMessage)
} else if (req.status == 408) {
createPopup("Alert:", internetServerError);
} else {
var messageArray = req.responseText;
if (messageArray != undefined || messageArray != "") {
var newArray = JSON.parse(messageArray);
if (newArray.length > 1) {
for (var i = 1; i < newArray.length; i++) {
createPopup("Alert:", newArray[i].message);
}
} else {
$.each(newArray, function () {
createPopup("Alert:", this.message);
});
}
} else {
createPopup("Alert", "Oops something went wrong please try again.")
}
}
}
});
From normal MVC
#using (Html.BeginForm("PayCash","User", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="col-sm-3 control-label" for="card-holder-name">Phone Number</label>
<div class="col-sm-6">
#*<input type="text" style="height:50px" class="form-control" name="card-holder-name" id="card-holder-name" placeholder="Phone Number">*#
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control", #style = "height:50px", #placeholder = "Phone Number", type = "number" })
#Html.ValidationMessageFor(m => m.PhoneNumber, null, validationStyle)
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="card-holder-name">Amount</label>
<div class="col-sm-6">
#*<input type="number" style="height:50px" class="form-control" name="card-holder-name" id="card-holder-name" placeholder="Amount">*#
#Html.TextBoxFor(m => m.Amount, new { #class = "form-control", #style = "height:50px", #placeholder = "Amount", type = "number" })
#Html.ValidationMessageFor(m => m.Amount, null, validationStyle)
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="expiry-month">Network</label>
<div class="col-sm-9">
<div class="row">
<div class="col-xs-6">
#Html.DropDownListFor(model => model.Natwork, new SelectList(Model.Networks, "Value", "Text"), "Select", new { #class = "form-control col-sm-2", #style = "height:50px" })
#Html.ValidationMessageFor(m => m.Natwork, null, validationStyle)
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="expiry-month"></label>
<div class="col-sm-offset-9">
<div class="row">
<div>
<input type="submit" style="height:50px;width:200px" value="Send" class="btn btn-success">
</div>
</div>
</div>
</div>
}
MVC function
[HttpPost]
public async Task<ActionResult> PayCash(PayVtuModel model)
{
if (ModelState.IsValid)
{
UserProfile userProfile = Permissions.CurrentUser();
bool isVtuSuccess = false;
string vtuReference = string.Empty;
AirVendResponse vend= await RequestManager.GetAirVendForUser(Convert.ToInt32(model.Natwork), model.PhoneNumber, model.Amount, userProfile.VtUUsername, userProfile.PinCode);
if (vend.VendResponse.ResponseCode == "0")
{
isVtuSuccess = true;
vtuReference = model.PhoneNumber;
CashActivity cashAct = new CashActivity()
{
IsVtuSuccess = isVtuSuccess,
Network = StringUtil.CheckNetwork(Convert.ToInt32(model.Natwork)),
PhoneNumber = vend.VendResponse.Msisdn,
RecordState = new RecordState(new Guid(userProfile.Id)),
Amount = Convert.ToDecimal(vend.VendResponse.Amount),
AVRef = vend.VendResponse.AVRef,
SellRef = vend.VendResponse.Ref
};
CashProvider.Add(cashAct);
return RedirectToAction("Index", "User");
}
else
{
ModelState.AddModelError("", "Error Code: " + vend.VendResponse.ResponseCode + "\n Message: " + vend.VendResponse.ResponseMessage);
}
}
return View(model);
}

Can't upload audio/video

Here is my html part I want to choose and post a file to method in the server.
<div class="control-group">
<input type="hidden" name="id" data-bind="value: id" />
<div class="controls">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
<embed height="50" width="100" data-bind="attr: { src: mediaUrl() }" />
</div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
</div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Choose a Audio/Voice</span> <span class="fileupload-exists">Change</span>
<input type="file" name="photoFile" class="default" />
</span><a data-bind="click: addMediaFile" href="#" class="btn fileupload-exists"
data-dismiss="fileupload">Save</a>
</div>
</div>
</div>
</div>
And here is addMediaFile javascript function in my ViewModel file
self.addMediaFile = function () {
utils.UIBlock();
$("#mediaForm").ajaxSubmit({
url: "api/Work/EditLibraryItemForMedia",
type: "POST",
success: function (result) {
self.mediaFilePath(result);
utils.UIUnBlock();
utils.showSuccess("Dosya kaydedilmiştir");
},
error: function () {
utils.UIUnBlock();
}
});
}
And finally here is my EditLibraryItemForMedia method in the server.
private Task<List<string>> UploadMediaFile()
{
string folderPath = ConfigurationManager.AppSettings["mediaFilesFolder"].ToString();
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(folderPath);
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(r => { return new List<string>(); });
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
string resizedImagesFolderPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Images/UploadedMedias/"));
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(
readTask =>
{
MultipartFormDataStreamProvider provider = readTask.Result;
return provider.FileData.Select(fileData =>
{
string itemId = provider.FormData["id"];
FileInfo fileInfo = new FileInfo(itemId);
string mimeType = GetMimeType(fileData.Headers.ContentDisposition.FileName);
string extension = "";
if (mimeType == "audio/mpeg3" || mimeType == "audio/x-mpeg-3" || mimeType == "video/mpeg" || mimeType == "video/x-mpeg")
{
extension = ".mp3";
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
// Add extensions to files
string fileName = itemId + extension;
string filePath = Path.Combine(folderPath, fileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Move(fileData.LocalFileName, filePath);
WorkService.UpdateMediaFile(itemId, Path.GetFileName(filePath));
return fileName;
}).ToList();
});
}
Actually problem is that I can't upload an audio and video using this procedure.

Categories