System.Data.Entity.Core.Entity Command Execution Exception - c#

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>
}

Related

How to get the data-id Send to another controller mvc

How to get the data-id sent to another controller in ASP.NET MVC?
The employee submits the form, automatically determines the id and department position, and then sends it to the manager for approval.
The manager clicks approval or reject on this page, and the form is sent to the next person for approval. At this step, the page prompts that id = null cannot be run. What should I do?
But Google background shows that I got this Id, how to send this Id to action?
public PartialViewResult saveStatus(int id, string Status, string AddDate, string Remark)
{
int approvalId;
if (id == 0 && Session["AppId"] == null)
{
var staff = db.Staffs.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
RequestForApproval ap = new RequestForApproval
{
RequestToStaffId = staff.Id,
RequestDate = DateTime.Now,
};
db.RequestForApprovals.Add(ap);
db.SaveChanges();
Session["AppId"] = ap.ReimbursementID;
approvalId = ap.Id;
}
else
{
approvalId = int.Parse(Session["AppId"].ToString());
}
ApprovalStatus temp = new ApprovalStatus
{
Id = approvalId,
Remark = Remark,
AddDate = DateTime.Now
};
db.ApprovalStatuses.Add(temp);
db.SaveChanges();
var df = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
return PartialView(df);
}
public JsonResult CreateStatus()
{
List<ApprovalStatus> mv = new List<ApprovalStatus>();
if(Session["AppId"] == null)
{
ViewBag.Ae = 0;
}
else
{
ViewBag.Ae = Session["AppId"];
int approvalId = int.Parse(Session["AppId"].ToString());
mv = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
}
return Json(mv);
}
public ActionResult AddRequestForApproval()
{
// var staffUser = db.StaffPositions.Where(a => a.Staff.UserName == System.Web.HttpContext.Current.User.Identity.GetUserId());
var rmid = Session["RmId"].ToString();
if (string.IsNullOrEmpty(rmid))
{
return RedirectToAction("Index");
}
int reimbursementId = int.Parse(rmid);
Session["RmId"] = null;
var Res = db.Reimbursements.Find(reimbursementId);
var managerId = GetByStaffId(Res.StaffId,reimbursementId);
RequestForApproval temp = new RequestForApproval();
temp.ReimbursementID = reimbursementId;
temp.RequestDate = DateTime.Now;
temp.RequestToStaffId = managerId;
db.RequestForApprovals.Add(temp);
db.SaveChanges();
return RedirectToAction("Index");
}
View:
#model Reimbursements.Models.RequesViewModel
#{
ViewBag.Title = "Index";
var add = Session["AppId"];
}
<h2>Index</h2>
<table class="table" id="table1">
<tr>
<th></th>
<th>
Staff Fname
</th>
<th>
RequestDate
</th>
<th></th>
</tr>
#foreach (var item in Model.GetReApproval)
{
<tr>
<td>
#item.ReimbursementId
</td>
<td>
#item.StaffName
</td>
<td>
#item.RequestDate
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-id="#item.RequerForApprovalId" data-target="#exampleModal" id="SelectBtn">Select</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="Title">Select and Confirm</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group" >
<input type="hidden" id="Reid" />
#Html.DropDownList("ApprovalStatus", null, new { #class = "btn btn-info",id="enumId" })
#*#Html.DropDownList("Index", ViewBag.DropDownList as SelectList,null, new { #class = "btn btn-info",#id="DropDownList" })*#
</div>
<hr />
<div class="form-group" style="visibility:visible" id="remarktext">
<label for="message-text" class="control-label">Remark:</label>
<textarea class="form-control" id="message-text" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
#*<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Confirme</button>*#
<button data-id="#item.ReimbursementId" class="btn btn-primary" id="Submit" #*onclick="location.href='#Url.Action("AddRequestForApproval","Reimbursements")'"*#>Submit</button>
<button class="btn btn-default" data-dismiss="modal" type="reset" id="Clear">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
</table>
#section Scripts {
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#table1").on('click', '#SelectBtn', function () {
$('#Submit').click('#enumId', function () {
var bid = $(this).attr('data-id');
var status = $("#enumId option:selected").val();
var mess = $('#message-text').val();
var Rmid;
console.log(bid, status, mess);
// var b = $("#NewId");
#*if ($("#NewId").val() == undefined) {
Rmid = 0;
} else {
Rmid = $("#NewId").val();
}
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("saveStatus")',
data: { id: bid, status: status, Remark: mess },
success: function (data) {
console.log(data);
status.val('').url(data);
mess.val('');
}, error: function (data) {
alert("error");
},
})*#
})
})
})
</script>
}
Instead of putting data-id there, you can just put it as value of a hidden filed in your form so that it gets posted when the form submitted:
<input type = "hidden" name="id" value="#item.ReimbursementId" />
If the value may change that you want to send different values when different buttons are clicked, then you can have a hidden input and set its value before submit:
$('#Submit').click('#enumId', function () {
var bid = $(this).data('id');
$('[name="id"]').val(bid);
// rest of your code....
});
Edit: if you are going to post it with ajax, please note that you should get data like:
$(this).data('id');

Duplicate Entity error when saving db even when the database is empty

I am making a MVC web app where one form affects many tables in the database. I have the page loading info into the Entity Framework, but I get a duplicate entity error when I run db.SaveChanges(). The database is completely empty so it has to be some error with the Save.
I suspect it has something to do with how I am uploading the data to the Framework, but I cannot figure out the correct way to do it.
Here is the Model:
public class BOGOModel
{
public BOGOModel()
{
}
public string PROMOTION_CODE { get; set; }
public string DESCRIPTION { get; set; }
public DateTime START_DATE_TIME { get; set; }
public DateTime END_DATE_TIME { get; set; }
public int[] BUY_MEMBERS { get; set; }
public int[] GET_MEMBERS { get; set; }
public int PERCENT_OFF { get; set; }
}
Here is the Controller:
public ActionResult BOGO()
{
return View();
}
[HttpPost]
public JsonResult BOGOSave(string MemberData)
{
BOGOModel ModelData = JsonConvert.DeserializeObject<BOGOModel>(MemberData);
PROMOTION Promotion = new PROMOTION();
Promotion.PROMOTION_CODE = ModelData.PROMOTION_CODE;
Promotion.DESCRIPTION = ModelData.DESCRIPTION;
Promotion.PROMOTION_TYPESysID = 12001;
Promotion.PROMOTION_APPLY_ASSysID = 98401;
Promotion.START_DATE_TIME = ModelData.START_DATE_TIME.ToString();
Promotion.END_DATE_TIME = ModelData.END_DATE_TIME.ToString();
db.PROMOTIONs.Add(Promotion);
AT_PROMOTION_ORG_UNIT PromotionOrgUnit = new AT_PROMOTION_ORG_UNIT();
PromotionOrgUnit.ORG_UNIT = "150";
PromotionOrgUnit.ORG_UNIT_TYPE = "Outlet";
PromotionOrgUnit.PARENT_ORG_UNIT = "DG";
db.AT_PROMOTION_ORG_UNIT.Add(PromotionOrgUnit);
ALLOCATED_ORG_UNIT AllocatedOrgUnit = new ALLOCATED_ORG_UNIT();
AllocatedOrgUnit.AT_PROMOTION_ORG_UNIT = PromotionOrgUnit;
db.ALLOCATED_ORG_UNIT.Add(AllocatedOrgUnit);
MP_PROMOTION__ALLOCATED_ORG_UNIT Map_P_A = new MP_PROMOTION__ALLOCATED_ORG_UNIT();
Map_P_A.PROMOTION = Promotion;
Map_P_A.ALLOCATED_ORG_UNIT = AllocatedOrgUnit;
db.MP_PROMOTION__ALLOCATED_ORG_UNIT.Add(Map_P_A);
PROMOTION_RULE BuyRule = new PROMOTION_RULE();
BuyRule.TARGET_TYPESysID = 1;
BuyRule.TARGET = 1;
db.PROMOTION_RULE.Add(BuyRule);
AT_PROMOTION_SET BuySetAttributes = new AT_PROMOTION_SET();
BuySetAttributes.name = "Buy";
BuySetAttributes.type = "BENEFIT";
BuySetAttributes.PROMOTION_SELECTIONSysID = 1;
db.AT_PROMOTION_SET.Add(BuySetAttributes);
PROMOTION_SET BuySet = new PROMOTION_SET();
BuySet.AT_PROMOTION_SET = BuySetAttributes;
db.PROMOTION_SET.Add(BuySet);
foreach(int upc in ModelData.BUY_MEMBERS)
{
AT_PROMOTION_MEMBER_KEY_VALUE MemberValue = new AT_PROMOTION_MEMBER_KEY_VALUE();
MemberValue.KEY_VALUE = upc;
db.AT_PROMOTION_MEMBER_KEY_VALUE.Add(MemberValue);
PROMOTION_MEMBER Member = new PROMOTION_MEMBER();
Member.LK_KEY_TYPE = db.LK_KEY_TYPE.Where(Type => Type.KEY_TYPESysID == 1).First();
Member.AT_PROMOTION_MEMBER_KEY_VALUE = MemberValue;
db.PROMOTION_MEMBER.Add(Member);
MP_PROMOTION_SET__PROMOTION_MEMBER Map_S_M = new MP_PROMOTION_SET__PROMOTION_MEMBER();
Map_S_M.PROMOTION_SET = BuySet;
Map_S_M.PROMOTION_MEMBER = Member;
db.MP_PROMOTION_SET__PROMOTION_MEMBER.Add(Map_S_M);
}
PROMOTION_RULE GetRule = new PROMOTION_RULE();
GetRule.TARGET_TYPESysID = 1;
GetRule.TARGET = 1;
GetRule.BENEFIT_TYPESysID = 5;
GetRule.BENEFIT = ModelData.PERCENT_OFF;
db.PROMOTION_RULE.Add(GetRule);
AT_PROMOTION_SET GetSetAttributes = new AT_PROMOTION_SET();
GetSetAttributes.name = "Get";
GetSetAttributes.type = "TARGET";
GetSetAttributes.PROMOTION_SELECTIONSysID = 1;
db.AT_PROMOTION_SET.Add(GetSetAttributes);
PROMOTION_SET GetSet = new PROMOTION_SET();
GetSet.AT_PROMOTION_SET = GetSetAttributes;
db.PROMOTION_SET.Add(GetSet);
foreach (int upc in ModelData.GET_MEMBERS)
{
AT_PROMOTION_MEMBER_KEY_VALUE MemberValue = new AT_PROMOTION_MEMBER_KEY_VALUE();
MemberValue.KEY_VALUE = upc;
db.AT_PROMOTION_MEMBER_KEY_VALUE.Add(MemberValue);
PROMOTION_MEMBER Member = new PROMOTION_MEMBER();
Member.LK_KEY_TYPE = db.LK_KEY_TYPE.Where(Type => Type.KEY_TYPESysID == 1).First();
Member.AT_PROMOTION_MEMBER_KEY_VALUE = MemberValue;
db.PROMOTION_MEMBER.Add(Member);
MP_PROMOTION_SET__PROMOTION_MEMBER Map_S_M = new MP_PROMOTION_SET__PROMOTION_MEMBER();
Map_S_M.PROMOTION_SET = GetSet;
Map_S_M.PROMOTION_MEMBER = Member;
db.MP_PROMOTION_SET__PROMOTION_MEMBER.Add(Map_S_M);
}
MP_PROMOTION__PROMOTION_SET Buy_Map_P_S = new MP_PROMOTION__PROMOTION_SET();
Buy_Map_P_S.PROMOTION = Promotion;
Buy_Map_P_S.PROMOTION_SET = BuySet;
db.MP_PROMOTION__PROMOTION_SET.Add(Buy_Map_P_S);
MP_PROMOTION__PROMOTION_SET Get_Map_P_S = new MP_PROMOTION__PROMOTION_SET();
Get_Map_P_S.PROMOTION = Promotion;
Get_Map_P_S.PROMOTION_SET = GetSet;
db.MP_PROMOTION__PROMOTION_SET.Add(Get_Map_P_S);
db.SaveChanges();
return Json("success");
}
Here is the View:
#model Promotion_Generator.Models.BOGOModel
#{
ViewBag.Title = "Buy One Get One";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2><b>Buy One Get One Free</b></h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<p class = "control-label col-md-2"><b>Promotion Code</b></p>
<div class="col-md-10 PC">
<input type="text" name="f-Promotion-Code" class="form-control f-Promotion-Code01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Description</b></p>
<div class="col-md-10 Desc">
<input type="text" name="f-Description" class="form-control f-Description01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Start Date Time</b></p>
<div class="col-md-10 SDT">
<input type="datetime" name="f-Start-Date-Time" class="form-control f-Start-Date-Time01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>End Date Time</b></p>
<div class="col-md-10 EDT">
<input type="datetime" name="f-End-Date-Time" class="form-control f-End-Date-Time01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Percent Off</b></p>
<div class="col-md-10 PO">
<input type="number" name="f-Percent-Off" class="form-control f-Percent-Off01" />
</div>
</div>
<div class="form-group col-md-10">
<h3><b>Buy Products</b></h3>
<table class="table" id="buytable">
<thead>
<tr>
<th>Product UPC</th>
<th />
<th />
</tr>
</thead>
<tbody>
<tr class="data-buy">
<td>
<input type="number" name="f-upc" class="form-control f-upc01" />
</td>
</tr>
</tbody>
</table>
<button type="button" id="btnAdd" class="btn btn-primary btn-md pull-right btn-sm classBuyAdd">Add More</button>
</div>
<div class="form-group col-md-10">
<h3><b>Get Products</b></h3>
<table class="table" id="gettable">
<thead>
<tr>
<th>Product UPC</th>
<th />
<th />
</tr>
</thead>
<tbody>
<tr class="data-get">
<td>
<input type="number" name="f-upc" class="form-control f-upc01" />
</td>
</tr>
</tbody>
</table>
<button type="button" id="btnAdd" class="btn btn-primary btn-md pull-right btn-sm classGetAdd">Add More</button>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" id="btnSubmit" value="Submit" class="btn btn-default">Submit</button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to Home", "Index", "Home")
</div>
#section scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".classBuyAdd", function () {
var rowCount = $('.data-contact-person').length + 1;
var contactdiv = '<tr class="data-buy">' +
'<td><input type="number" name="f-upc' + rowCount + '" class="form-control f-upc01" /></td>' +
'<td><button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
'</tr>';
$('#buytable').append(contactdiv);
});
});
$(document).ready(function () {
$(document).on("click", ".classGetAdd", function () {
var rowCount = $('.data-contact-person').length + 1;
var contactdiv = '<tr class="data-get">' +
'<td><input type="number" name="f-upc' + rowCount + '" class="form-control f-upc01" /></td>' +
'<td><button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
'</tr>';
$('#gettable').append(contactdiv);
});
});
$(document).on("click", ".deleteContact", function () {
$(this).closest("tr").remove();
});
function getAllData() {
var data = [];
$('div.PC').each(function () {
var upc = $(this).find('.f-Promotion-Code01').val();
data.push(upc);
});
$('div.Desc').each(function () {
var upc = $(this).find('.f-Description01').val();
data.push(upc);
});
$('div.SDT').each(function () {
var upc = $(this).find('.f-Start-Date-Time01').val();
data.push(upc);
});
$('div.EDT').each(function () {
var upc = $(this).find('.f-End-Date-Time01').val();
data.push(upc);
});
var UPC1 = []
$('tr.data-buy').each(function () {
var upc = $(this).find('.f-upc01').val();
UPC1.push(upc);
});
var UPC2 = [];
$('tr.data-get').each(function () {
var upc = $(this).find('.f-upc01').val();
UPC2.push(upc);
});
$('div.PO').each(function () {
var upc = $(this).find('.f-Percent-Off01').val();
data.push(upc);
});
var alldata = {
'PROMOTION_CODE': data[0],
'DESCRIPTION': data[1],
'START_DATE_TIME': data[2],
'END_DATE_TIME': data[3],
'BUY_MEMBERS': UPC1,
'GET_MEMBERS': UPC2,
'PERCENT_OFF': data[4],
}
console.log(alldata);
return alldata;
}
$("#btnSubmit").click(function () {
var data = JSON.stringify(getAllData());
console.log(data);
$.ajax({
url: 'BOGOSave',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'MemberData': data }),
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
});
</script>
}
Any help would be appreciated. Thanks!
Edit 1: Here is the specific error message:
{"Violation of PRIMARY KEY constraint 'PK__AT_PROMO__36BD5C21B6ADDCDF'. Cannot insert duplicate key in object 'dbo.AT_PROMOTION_MEMBER_KEY_VALUE'. The duplicate key value is (0).\r\nThe statement has been terminated."}
The schema is way to large to fit in this post, but here is the table mentioned in the error:
CREATE TABLE [AT_PROMOTION_MEMBER_KEY_VALUE] (
[PROMOTION_MEMBER_KEY_VALUESysID] int PRIMARY KEY NOT NULL,
[KEY_VALUE] bigint NOT NULL,
[sku] varchar(MAX) NULL,
[owner] varchar(10) NULL,
[owner_type] int FOREIGN KEY REFERENCES [LK_OWNER_TYPE] ([OWNER_TYPESysID]) NULL,
[product_group_type] varchar(10) NULL
);
OK, I fixed the problem. It turns out that I didn't auto increment the primary key and since I wasn't manually setting it either it was always 0. Even though there wasn't anything in the database it still couldn't insert because I was trying to create two items and they had the same ID. Thanks to the comments that helped to figure this out.

Sortable, draggable, orderable table + mvc not updating order correctly

I'm trying to add an orderable table to my view. The sorting works when doing it in the View New.cshtml. It uses jQuerys sortable. If I add some instructions (1-5 in this case) I can move them around thanks to the sortable script. But when I try to add a new instruction after the reordering, the order change from:
to
I guess it has something to do with the hidden form
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #id = "Number"})
It needs to update its value when I reorder the fields in the sortable table.
What am I missing here?
RecipeController.cs
public ActionResult Create(NewRecipeViewModel viewModel, string command)
{
//...more code...
var instructionList = new List<Instruction>();
if (viewModel.Recipe.Instructions != null)
{
for (int i = 0; i < viewModel.Recipe.Instructions.Count; i++)
{
var instruction = new Instruction
{
Id = viewModel.Recipe.Instructions[i].Id,
Name = viewModel.Recipe.Instructions[i].Name,
Number = viewModel.Recipe.Instructions[i].Number
};
instructionList.Add(instruction);
}
}
if (command.Equals("AddInstruction"))
{
var instruction = new Instruction
{
Name = viewModel.NewInstruction.Name,
Number = viewModel.Recipe.Instructions.Count + 1
};
recipe.Instructions.Add(instruction);
viewModel.Recipe = recipe;
return View("New", viewModel);
}
//...more code...
}
New.cshtml
<div class="form-group" style="margin-top: 170px;">
<label class="col-md-2 control-label">
Lägg till instruktion:
</label>
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewInstruction.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group" style="margin-top: 300px;">
<label class="col-md-2 control-label">
</label>
<div class="col-md-10">
<button type="submit" name="command" value="AddInstruction" class="btn btn-primary">Add instruction</button>
</div>
</div>
<div class="form-group" style="margin-top: 100px;">
<label class="col-md-2 control-label">
Instructions:
</label>
<div class="col-md-10">
<table class="table table-bordered table-hover pagin-table" style="margin-top: 10px">
<thead>
<tr bgcolor="#f5f5f5">
<th>Order:</th>
<th>Instruction:</th>
</tr>
</thead>
<tbody id="sortable">
#if (Model.Recipe.Instructions != null)
{
for (int i = 0; i < Model.Recipe.Instructions.Count; i++)
{
<tr>
#Html.HiddenFor(m => Model.Recipe.Instructions[i].Id)
<td class="order">
#Model.Recipe.Instructions[i].Number
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #id = "Number"})
</td>
<td>
#Model.Recipe.Instructions[i].Name
#Html.HiddenFor(m => m.Recipe.Instructions[i].Name)
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#sortable').sortable({
update : function(event, ui) {
$('td.order').each(function(index) {
var order = index + 1;
$(this).find('span').text(order);
$(this).find('.Number').val(order);
});
}
});
});
</script
EDIT:
Added
instructionList.Sort((s1, s2) => s1.Number.CompareTo(s2.Number));
to RecipeController.cs. The rest is credit to Stephen Muecke.
RecipeController.cs
public ActionResult Create(NewRecipeViewModel viewModel, string command)
{
//...more code...
var instructionList = new List<Instruction>();
if (viewModel.Recipe.Instructions != null)
{
for (int i = 0; i < viewModel.Recipe.Instructions.Count; i++)
{
var instruction = new Instruction
{
Id = viewModel.Recipe.Instructions[i].Id,
Name = viewModel.Recipe.Instructions[i].Name,
Number = viewModel.Recipe.Instructions[i].Number
};
instructionList.Add(instruction);
}
instructionList.Sort((s1, s2) => s1.Number.CompareTo(s2.Number));
}
//...more code...
}
New.cshtml
#* More code *#
<td class="order">
<span>#Model.Recipe.Instructions[i].Number</span>
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new {#class = "Number"})
</td>
#* More code *#
<script type="text/javascript">
$(document).ready(function() {
$('#sortable').sortable({
update : function(event, ui) {
$('td.order').each(function(index) {
var order = index + 1;
$(this).find('span').text(order);
$(this).find('.Number').val(order);
});
}
});
});
</script
Your selector in the update function is incorrect and would return undefined (you are missing the # (id selector) and in anycase the $ creates a jQuery object, so it would be .val(...), not value=....
However using $('#Number').val(index + 1) will not work correctly since it would only ever update the first element with id="Number". Duplicateid` attributes are invalid html.
Use a class name and relative selectors instead. Change the html to
<td class="order">
<span>#Model.Recipe.Instructions[i].Number</span>
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #class = "Number"})
</td>
and then the script to
$('#sortable').sortable({
update : function(event, ui) {
$('td.order').each(function(index) {
var order = index + 1;
$(this).find('span').text(order );
$(this).find('.Number').val(order );
});
}
});
In your markup, change Model to your projected variable m within your 'Html.HiddenFor()' HTML helpers.
<tr>
#Html.HiddenFor(m => m.Recipe.Instructions[i].Id)
<td class="order">
#Model.Recipe.Instructions[i].Number
#Html.HiddenFor(m => m.Recipe.Instructions[i].Number, new { #id = "Number"})
</td>
<td>
#Model.Recipe.Instructions[i].Name
#Html.HiddenFor(m => m.Recipe.Instructions[i].Name)
</td>
</tr>

How to display messages in view in MVC4 when model does not return any data?

Hi I am developing application where i have 5 textboxes and search button. When i enter data into textbox and click on search, corresponding matched data of database will be displayed in below table. I have implemented paging and it works fine. Below is the code.
[HttpGet]
public ActionResult Index(int? clientId, string dateofAction, int? doc_typeid, string employeeID,string citizenId,int? currentFilter, string filterdateTime,int? filterdocType,string filteredemployeeID,string filteredcitizenId,int? page)
{
ViewBag.curpageNumber = page;
logDetailsEnumeration model = new logDetailsEnumeration();
DB_KYC3Entities db = new DB_KYC3Entities();
var docTypes = from c in db.tm_doc_type select c;
if (clientId != null)
{
page = 1;
}
else
{
clientId = currentFilter;
}
if(dateofAction!=null)
{
page = 1;
}
else
{
dateofAction = filterdateTime;
}
if(doc_typeid != null)
{
page = 1;
}
else
{
doc_typeid = filterdocType;
}
if(employeeID!=null)
{
page = 1;
}
else
{
employeeID = filteredemployeeID;
}
if(citizenId!=null)
{
page = 1;
}
else
{
citizenId = filteredcitizenId;
}
ViewBag.CurrentFilter = clientId;
ViewBag.filterdateTime = dateofAction;
int pageSize = 8;
int pageNumber = (page ?? 1);
VerificationLogBAL obj = new VerificationLogBAL();
int docType = obj.GetDocDetails(doc_typeid?? default(int));
List<logDetails> logDetails = obj.getlogDetails(clientId?? default(int), dateofAction, docType, employeeID, citizenId);
IPagedList<logDetails> pagedLog = logDetails.ToPagedList(pageNumber, pageSize);
model = new logDetailsEnumeration()
{
pageNum= pageNumber,
doc_typeid = doc_typeid,
Count=logDetails.Count,
employeeID = employeeID,
citizenId= citizenId,
logDetails = pagedLog,
doctype_name=new SelectList(docTypes, "doc_typeid", "doctype_name")
};
return View("Index",model);
}
}
This is my view code.
#using (Html.BeginForm("Index", "VerificationLog", FormMethod.Get))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="message"></div>
<div class="loginUsernamePassword">
<i class="fa fa-user"></i>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dataTable tableHover">
<tr>
<th width="8%" scope="col">Client ID</th>
<th width="20%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.clientId, ViewBag.CurrentFilter as string, new { #id = "clientId", #placeholder = "Client ID", #class = "form-control", #maxlength = 20 })
</div>
</th>
<th width="10%" scope="col">Date Of Action</th>
<th width="20%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.dateofAction, ViewBag.filterdateTime as string, new { #id = "dateofAction", #placeholder = "Date Of Action", #class = "txtBox form-control calender validate[required]" })
#*#Html.TextBox("dateofAction", ViewBag.filterdateTime as string, new { #id = "dateofAction", #placeholder = "Date Of Action", #class = "txtBox form-control calender validate[required]" })*#
</div>
</th>
<th width="15%" scope="col">Type Of Document</th>
<th width="17%" scope="col">
<div class="form-box form-box-default">
#*#Html.TextBox("typeofDocument", ViewBag.filterdateTime as string, new { #id = "typeofDocument", #placeholder = "Type Of Document", #class = "form-control", #maxlength = 20 })*#
#Html.DropDownListFor(x=>x.doc_typeid,Model.doctype_name,"Select",new { #class = "form-control" })
</div>
</th>
</tr>
<tr>
<th width="15%" scope="col">Employee ID</th>
<th width="17%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.employeeID, Model.employeeID, new { #id = "employeeID", #placeholder = "Employee ID", #class = "form-control", #maxlength = 20 })
</div>
</th>
<th width="15%" scope="col">Citizen ID</th>
<th width="17%" scope="col">
<div class="form-box form-box-default">
#Html.TextBoxFor(x=>x.citizenId, Model.citizenId, new { #id = "citizenId", #placeholder = "Citizen ID", #class = "form-control", #maxlength = 20 })
</div>
</th>
<th width="10%" scope="col" colspan="2">
<input type="submit" value="Search" class="btn btn-primary btn-cons search" />
</tr>
</table>
</div>
}
</div>
#if (Model != null && Model.logDetails.Count != 0)
{
<br />
<h2>Verification Log</h2>
<br />
<div id="GridDetails">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dataTable tableHover">
<tr>
#*<th>#Html.ActionLink("Label", "Index", new { sortOrder = ViewBag.LabelSortParm, currentFilter = ViewBag.CurrentFilter, filterdateTime = ViewBag.filterdateTime, filterdocType = Model.doc_typeid, filteredemployeeID = Model.employeeID, filteredcitizenId = Model.citizenId, Page = ViewBag.curpageNumber })</th>*#
<th>Label</th>
<th>Value</th>
<th>UpdatedOn</th>
<th>UpdatedBy</th>
<th>UpdatedStatus</th>
<th>RejectComment</th>
</tr>
#foreach (var group in Model.logDetails)
{
<tr>
<td>#group.contentLabel</td>
<td>#group.contentValue</td>
<td>#group.updatedOn</td>
<td>#group.updatedBy</td>
<td>#group.updatedStatus</td>
<td>#group.rejectComment</td>
</tr>
}
</table>
#Html.PagedListPager(Model.logDetails, page => Url.Action("Index",
new { page, currentFilter = ViewBag.CurrentFilter, filterdateTime=ViewBag.filterdateTime, filterdocType= Model.doc_typeid, filteredemployeeID = Model.employeeID, filteredcitizenId = Model.citizenId }))
Page #(Model.logDetails.PageCount < Model.logDetails.PageNumber ? 0 : Model.logDetails.PageNumber) of #Model.logDetails.PageCount
</div>
I am having problem in displaying message No records found. If i try to put No records found by checking following property if(Model!=null) then When the first time page loads then also it display No records found. I want to display only after clicking on submit button and if there are no matching records found. Is there any way I can implement solution in above scenario? Thanks
You could add a new property to the model that would only be set when the search has been completed. This would indicate if there were no records found and you could use logic in the view to display an appropriate message.

mvc ajax form post null list issue

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";
}
}

Categories