How do i do crud from multiple tables in visual studio mvc - javascript

Hi new to visual studio and mvc in general and im trying to make a mvc crud including two tables. I have so far managed to do Create and List in index but i have having problem trying to edit,delete and show details.
Desc Class
[Table("klsm_InvoiceDesc")]
public class Desc
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public int DescNo { get; set; }
public string Principal { get; set; }
public string ChargeCode { get; set; }
public string Quantity { get; set; }
public string Description { get; set; }
public string UnitPrice { get; set; }
public string Amount { get; set; }
public string ForeignAmount { get; set; }
public string EL1 { get; set; }
public string EL2 { get; set; }
public string ShortName { get; set; }
public string InvoiceType { get; set; }
public string PONumber { get; set; }
public string Batch { get; set; }
public string CCVBatch { get; set; }
public string PaidAmount { get; set; }
public string Paid { get; set; }
public string TT { get; set; }
public string BankCode { get; set; }
}
College Class
[Table("klsm_Invoice")]
public class College
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public decimal Amount { get; set; }
public decimal ForeignAmount { get; set; }
public string UserCreated { get; set; }
public string UserModified { get; set; }
public int AccMonth { get; set; }
public int AccYear { get; set; }
public string AccStatus { get; set; }
public string Status { get; set; }
public string PaidStatus { get; set; }
public string Principal { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public string EL1 { get; set; }
public string InvoiceType { get; set; }
public string CurrencyType { get; set; }
public decimal ExchangeRate { get; set; }
public string GSTChecked { get; set; }
public DateTime PaymentSchedule { get; set; }
public string PaymentMode { get; set; }
public string CashAdvance { get; set; }
}
my home controller
public class HomeController : Controller
{
// GET: Home
DataContext db = new DataContext();
public ActionResult Index()
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice").ToList();
return View(data);
//List<College> klsm_Invoice = db.klsm_Invoice.ToList();
//return View(klsm_Invoice);
}
// GET: Home/Details/5
public ActionResult Details(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// GET: Home/Edit/5
public ActionResult Edit(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Edit/5
[HttpPost]
public ActionResult Edit(string id, College collection)
{
db.Entry(collection).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Home/Delete/5
public ActionResult Delete(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Delete/5
[HttpPost]
public ActionResult Delete(string id, College collection)
{
try
{
// TODO: Add delete logic here
int result = db.Database.ExecuteSqlCommand("DELETE FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Search(string InternalInvoiceNo)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo = '" + InternalInvoiceNo + "' ").ToList();
return PartialView("DefaultIndex", data);
}
// GET: Home/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult CreateInvoice(string invoiceDetailsList, string internalInvoiceNo, string invoiceNo, DateTime invoiceDate, string customerName, int year, int month, string amount, string foreignAmount, string userCreated, string userModified, int accMonth, int accYear, string accStatus, string status, string paidStatus, string principal, DateTime dateCreated, DateTime dateModified, string el1, string invoiceType, string currrencyType, string exchangeRate, string gstChecked, DateTime paymentSchedule, string paymentMode, string cashAdvance)
{
List<Desc> detailsList = JsonConvert.DeserializeObject<List<Desc>>(invoiceDetailsList);
var addingmaster = new College();
{
addingmaster.InternalInvoiceNo = internalInvoiceNo;
addingmaster.InvoiceNo = invoiceNo;
addingmaster.InvoiceDate = Convert.ToDateTime(invoiceDate);
addingmaster.CustomerName = customerName;
addingmaster.Year = year;
addingmaster.Month = month;
addingmaster.Amount = Convert.ToDecimal(amount);
addingmaster.ForeignAmount = Convert.ToDecimal(foreignAmount);
addingmaster.UserCreated = userCreated;
addingmaster.UserModified = userModified;
addingmaster.AccMonth = accMonth;
addingmaster.AccYear = accYear;
addingmaster.AccStatus = accStatus;
addingmaster.Status = status;
addingmaster.PaidStatus = paidStatus;
addingmaster.Principal = principal;
addingmaster.DateCreated = Convert.ToDateTime(dateCreated);
addingmaster.DateModified = Convert.ToDateTime(dateModified);
addingmaster.EL1 = el1;
addingmaster.InvoiceType = invoiceType;
addingmaster.CurrencyType = currrencyType;
addingmaster.ExchangeRate = Convert.ToDecimal(exchangeRate);
addingmaster.GSTChecked = gstChecked;
addingmaster.PaymentSchedule = Convert.ToDateTime(paymentSchedule);
addingmaster.PaymentMode = paymentMode;
addingmaster.CashAdvance = cashAdvance;
db.klsm_Invoice.Add(addingmaster);
db.SaveChanges();
}
foreach (var item in detailsList)
{
Desc addingdetails = new Desc();
addingdetails.InternalInvoiceNo = item.InternalInvoiceNo;
addingdetails.InvoiceNo = item.InvoiceNo;
addingdetails.DescNo = item.DescNo;
addingdetails.Principal = item.Principal;
addingdetails.ChargeCode = item.ChargeCode;
addingdetails.Quantity = item.Quantity;
addingdetails.Description = item.Description;
addingdetails.UnitPrice = item.UnitPrice;
addingdetails.Amount = item.Amount;
addingdetails.ForeignAmount = item.ForeignAmount;
addingdetails.EL1 = item.EL1;
addingdetails.EL2 = item.EL2;
addingdetails.ShortName = item.ShortName;
addingdetails.InvoiceType = item.InvoiceType;
addingdetails.PONumber = item.PONumber;
addingdetails.Batch = item.Batch;
addingdetails.CCVBatch = item.CCVBatch;
addingdetails.PaidAmount = item.PaidAmount;
addingdetails.Paid = item.Paid;
addingdetails.TT = item.TT;
addingdetails.BankCode = item.BankCode;
//addingdetails.Id = item.Id;
db.klsm_InvoiceDesc.Add(addingdetails);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
I have yet to add views for the needed help so anything will help rn

Related

Have to show Model data into View using JavaScript MVC C#

I have page where I save user, contact and address details. The users could have multiple contact and address, So I have added the control to populate dynamically.
Form is working fine, except if any exception occurrs, the controller action return view with model.
This follows the structure of Model:
Model
public class UserModel
{
public UserDetail User { get; set; }
public IList<UserContact> Contact { get; set; }
public IList<UserAddress> Address { get; set; }
}
Contact Model :
public partial class UserContact
{
public int Id { get; set; }
public int UserId { get; set; }
public string ContactType { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
Address Model
public partial class UserAddress
{
public int Id { get; set; }
public int UserId { get; set; }
public string AddressType { get; set; }
public string AddressName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostCode { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
When value return, the following function suppose to check the Contact and Address and then then populate each record in dynamic created input section in view.
<script type="text/javascript">
$(document).ready(function () {
AddDynamicData();
function AddDynamicData() {
var valuesContacts = eval('#Html.Raw(Json.Encode(Model.Contact))');
var valuesAddresses = eval('#Html.Raw(Json.Encode(Model.Address))');
if (valuesContacts != null) {
var iContact = 0;
$(valuesContacts).each(function () {
$("#divContact").append(GetDynamicContact(iContact++, valuesContacts.contactType, valuesContacts.mobile, valuesContacts.email));
});
}
if (valuesAddresses != null) {
var iAddress = 0;
$(valuesAddresses).each(function () {
$("#divAddress").append(GetDynamicAddress(iAddress++, valuesAddresses.addressType, valuesAddresses.addressName, valuesAddresses.addressLine1, valuesAddresses.addressLine2, valuesAddresses.city, valuesAddresses.state, valuesAddresses.postCode));
});
}
}
</script>
The Function does not work properly, It does create the field but does not populate the user input data into textbox... Please advise how to fix the same and how to populate the records in view....
Added the View after submitting the form
<Update>
#Updated New Code with function & added screenshot
</Update>

Filter Not Filtering Records

I'm trying to find records in $scope.employeesthat do not have a matching record in $scope.allEmployeeGroups, but the filter is not Filtering records, even though I know for sure that there should only be a few unmatched, it returns all of the records. For each record, the indexOf == -1 when I know that it should not. I can't figure out what I am doing wrong. Here is my code:
function getNonGroupEmployees() {
var arr = $scope.employees.filter(function (item) {
return $scope.allEmployeeGroups.indexOf(item.EmployeeId) === -1;
})
return arr;
}
Employee Object:
public System.Guid EmployeeId { get; set; }
public Nullable<System.Guid> SiteId { get; set; }
public string SiteName { get; set; }
public string DisplayName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public string Alias { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public string SsnLastFour { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
public bool IsLoginEnabled { get; set; }
public Nullable<System.DateTime> LastLogin { get; set; }
public Nullable<System.Guid> SignatureTypeId { get; set; }
public string SignatureType { get; set; }
public string NumberHome { get; set; }
public string NumberCell { get; set; }
public bool IsSuperUser { get; set; }
public bool IsDeleted { get; set; }
public System.DateTime Created { get; set; }
public System.DateTime LastModified { get; set; }
public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
public string ApiKey { get; set; }
Group Object:
public Guid EmployeeGroupId { get; set; }
public Guid SiteId { get; set; }
public Guid EmployeeId { get; set; }
public Guid SiteGroupId { get; set; }
public bool IsDeleted { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
public Guid? ModifiedByEmployeeId { get; set; }
public string SiteName { get; set; }
public string EmployeeName { get; set; }
public string SiteGroupName { get; set; }
public string ModifiedByEmployeeName { get; set; }
Any assistance is greatly appreciated.
Instead of searching object with .IndexOf(), use property matching. Object will not match if two objects do not have same reference.
Try with following code block:
function getNonGroupEmployees() {
var arr = $scope.employees.filter(function (item) {
return $scope.allEmployeeGroups.find(function(p){
return p.EmployeeId == item.EmployeeId
})=== null;
})
return arr;
}
AS requested here are data structures:
Employee:
public System.Guid EmployeeId { get; set; }
public Nullable<System.Guid> SiteId { get; set; }
public string SiteName { get; set; }
public string DisplayName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public string Alias { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public string SsnLastFour { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
public bool IsLoginEnabled { get; set; }
public Nullable<System.DateTime> LastLogin { get; set; }
public Nullable<System.Guid> SignatureTypeId { get; set; }
public string SignatureType { get; set; }
public string NumberHome { get; set; }
public string NumberCell { get; set; }
public bool IsSuperUser { get; set; }
public bool IsDeleted { get; set; }
public System.DateTime Created { get; set; }
public System.DateTime LastModified { get; set; }
public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
public string ApiKey { get; set; }
Employee Group
public Guid EmployeeGroupId { get; set; }
public Guid SiteId { get; set; }
public Guid EmployeeId { get; set; }
public Guid SiteGroupId { get; set; }
public bool IsDeleted { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
public Guid? ModifiedByEmployeeId { get; set; }
public string SiteName { get; set; }
public string EmployeeName { get; set; }
public string SiteGroupName { get; set; }
public string ModifiedByEmployeeName { get; set; }
Thanks to answer found Here, here is what eventually worked:
function getNonGroupEmployees() {
var result = $scope.employees.filter(function (o1) {
return !$scope.allEmployeeGroups.some(function (o2) {
return o1.EmployeeId === o2.EmployeeId; // assumes unique id
});
})
return result;
}

Javascript ajax passing dynamically created json object to a web service

I have a web service function that has an object parameter,
Function from controller
public string Post([FromBody]LoanApplication value)
{
LoanApplicationDAO appDAO = new LoanApplicationDAO();
string res = "";
res = appDAO.ReleaseLoanApplication(value);
if (res == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
return res;
}
LoanApplication contains
public class LoanApplication
{
public string AccountAddress { get; set; }
public string AccountName { get; set; }
public string AccountNumber { get; set; }
public string AccountTag { get; set; }
public string ApplicationNumber { get; set; }
public string ApplicationType { get; set; }
public string Approver { get; set; }
public string BSPTagging { get; set; }
public string BuyOutAmount { get; set; }
public string CIFKey { get; set; }
public string ClassificationEconomicActivity { get; set; }
public string ClassificationSizeOfFirm { get; set; }
public string CoMaker1 { get; set; }
public string CoMaker2 { get; set; }
public string CoMakerName1 { get; set; }
public string CoMakerName2 { get; set; }
public string CreditLimit { get; set; }
public string DateGranted { get; set; }
public string DepEdDivision { get; set; }
public string DepEdEmployeeID { get; set; }
public string DepEdRegion { get; set; }
public string DepEdStation { get; set; }
public string Disbursement { get; set; }
public string DocStamps { get; set; }
public string DOSRIField { get; set; }
public string EmailAddress { get; set; }
public string FirstPaymentDate { get; set; }
public string GroupCode { get; set; }
public string GroupName { get; set; }
public string Insurance { get; set; }
public string InterestRate { get; set; }
public string KnockedOffAccountNumber { get; set; }
public string KnockedOffAmount { get; set; }
public string LandlineNumber { get; set; }
public string LoanAmount { get; set; }
public string LPOCode { get; set; }
public string Maker { get; set; }
public string MaturityDate { get; set; }
public string MobileNumber { get; set; }
public string MonthlyAmort { get; set; }
public string MothersMaidenName { get; set; }
public string NDaysDiscount { get; set; }
public string NoOfInstall { get; set; }
public string PaymentFrequency { get; set; }
public string PayOutMode { get; set; }
public string PEPTagging { get; set; }
public string Product { get; set; }
public string Purpose { get; set; }
public string Security { get; set; }
public string ServiceFees { get; set; }
public string SourceOfPayment { get; set; }
public string SpouseMobileNumber { get; set; }
public string SpouseName { get; set; }
public string Term { get; set; }
public string AOUserID { get; set; }
public string AOName { get; set; }
public string LSOCode { get; set; }
public string IsBranch { get; set; }
}
When I use the debugging mode from VS 2012 the LoanObj accountname and accountnumer is null, but when i check my pass value from ajax it has value, checked it from google chromes console
sample format of the value from ajax jsonObj: { AccountName:"test name", AccountAddress: "test address", etc.. }
my ajax function
$('body').on('click', '#btnSubmit', function () {
var jsonObj = {};
$('#lfs_form tbody input[type="text"]').each(function () {
jsonObj[this.id] = this.value;
});
var req2 =
$.ajax({
type: 'post',
url: '../lfsapi/loanapplication/',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({
jsonObj
//AccountAddress: jsonObj['AccountAddress']
})
});
req.error(function (request, status, error) {
alert(request.responseJSON['Message']);
});
req.done(function (data) {
});
});
But when I try
data: JSON.stringify({
AccountName: jsonObj['AccountName'],
AccountNumber: jsonObj['AccountNumber']
})
It works, and successfully pass the expected values to function, my sample only is 2 objects but in my real code i have more than 40 objects thats why i tried using loop..anyone knows how can i fix the issue?
thank you
Additional code, to populate my form
$.ajax({
type: 'get',
url: '../lfsapi/loanapplication/',
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
req.error(function (request, status, error) {
alert(request.responseJSON['Message']);
});
req.done(function (data) {
var toappend = '';
$.each(data, function (key, val) {
toappend += '<tr>';
toappend += '<td>' + val + '</td><td><input style="width:500px;" type="text" id=' + val + ' /></td>';
toappend += '</tr>';
});
toappend += '<tr><td align="right" colspan="2"><button id="btnSubmit" type="button">Submit</button></td></tr>';
$('#lfs_form tbody').append(toappend);
});
There are several mistakes I noticed in your code :
firstly you are using jsonObj[this.id] for assigning value to object
members. so this.id should be AccountName or AccountNumber else it
would not assign value to required members.
secondly, remove extra brakets {} from JSON.stringify and use like this
JSON.stringify(
jsonObj
);
Solve the issue by
data: JSON.stringify(jsonObject)
thank you all

How to display foreign key value from a model to a cascaded dropdown list in mvc5?

I'm still new to mvc5 and had very little knowledge with javascript. I know that my cascading works but I'm having trouble with the display part. What I want to do is have 2 dropdown list. 1 containing all customer names and the 2nd will have a list of their pending transactions. Basically 1st dropdown will have customer names while the 2nd will have video titles. Please check my code where I did wrong. Why I can't display the video titles. BTW I tried other properties in my transactions and I can display them. That's how I know that my cascading is not the problem.
Models
//Transaction Model
TransactionID { get; set; }
public int CustomerID { get; set; }
public virtual Customers CustomerName { get; set; }
public int VideoID { get; set; }
public virtual Videos Videos { get; set; }
public int Quantity { get; set; }
[ReadOnly(true)]
public DateTime? TransactionDate { get; set; }
[ReadOnly(true)]
public DateTime? DueDate { get; set; }
[ReadOnly(true)]
public Decimal Cost { get; set; }
[ReadOnly(true)]
public String ReturnStatus { get; set;}
//Customers Model
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerContact { get; set; }
//Video Model
public int VideoID { get; set; }
public string VideoTitle { get; set; }
public int CategoryID { get; set; }
public virtual Category VideoCategory { get; set; }
[Range(0,99)]
public int VideoIn { get; set; }
[Range(0,99)]
public int VideoOut { get; set; }
Conroller
public ActionResult CustomerList()
{
var customers = db.Customers.OrderBy(x => x.CustomerID).ToList();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(
customers,
"CustomerID",
"CustomerName"), JsonRequestBehavior.AllowGet
);
}
return View(customers);
}
public ActionResult Transact(int cusId)
{
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE").ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
transact,
"TransactionID",
"VideoTitle"), JsonRequestBehavior.AllowGet
);
return View(transact);
}
I figure out a solution after hours of trial an error. What I did is I added a join in my query.
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE")
.Join(db.Videos,
v => v.VideoID,
t => t.VideoID,
(transaction, videos) => new {
TransactionID = transaction.TransactionID,
VideoTitle = videos.VideoTitle }).ToList();

how to send json data to serializable class

there is a problem when send json data to serializable class. On client side when i check data on browser it is true but on server side the fields of serializable class are null.
Client side (using dojo) : on the debugger line fileds of ticket object are assigned
var Ticket = {
ProductId: productId,
Type: ticketType
};
DataService.xhrPageMethodJson("api/Tickets/MyTickets"
, dojo.toJson(Ticket)
, {
success: function (data) {
debugger
loadSubPage(getRoot("Support/Tickets.aspx?mode=list"));
},
error: function (err) {
LoadingOverlay.hide();
}
});
Web Method: On this method ticket.ProductId, ticket.Type fields has default value or null.
[HttpPost]
[AcceptVerbs("POST")]
[ActionName("MyTickets")]
[Authorize]
public void MyTickets([FromBody]Ticket ticket)
{
DataTable myTickets = db.Tickets.MyTickets(Globals.LogonUser.User.Id, ticket.ProductId, ticket.Type);
WebContext.Session["Tickets"] = myTickets;
}
Ticket class:
[Serializable]
[EntityTable(Name = "Tickets")]
public class Ticket : Entity
{
public override int Id { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public DateTime SentDate { get; set; }
[JoinField(typeof(User), "Id")]
public int SenderUserId { get; set; }
[JoinField(typeof(Product), "Id")]
public int ProductId { get; set; }
[JoinField(typeof(TicketImportanceLevel), "Id")]
public int ImportanceLevel { get; set; }
public int Analyze { get; set; }
public int SolutionTransactionId { get; set; }
[JoinField(typeof(TicketType), "Id")]
public int Type { get; set; }
public int Status { get; set; }
public int AssignedUserId { get; set; }
public float Score { get; set; }
}
I have solved this problem with marking properties as data member and class as data contract. Here I am sharing new class structure:
[Serializable]
[DataContract]
[EntityTable(Name = "Tickets")]
public class Ticket : Entity
{
[DataMember]
public override int Id { get; set; }
[DataMember]
public string Subject { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public DateTime SentDate { get; set; }
[JoinField(typeof(User), "Id")]
[DataMember]
public int SenderUserId { get; set; }
[JoinField(typeof(Product), "Id")]
[DataMember]
public int ProductId { get; set; }
[JoinField(typeof(TicketImportanceLevel), "Id")]
[DataMember]
public int ImportanceLevel { get; set; }
[DataMember]
public int Analyze { get; set; }
[DataMember]
public int SolutionTransactionId { get; set; }
[JoinField(typeof(TicketType), "Id")]
[DataMember]
public int Type { get; set; }
[DataMember]
public int Status { get; set; }
[DataMember]
public int AssignedUserId { get; set; }
[DataMember]
public float Score { get; set; }
}

Categories

Resources