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

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>

Related

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

Service Return Empty Lists To Api Controller

I am working in service fabrics micro services , where i need to fetch record for an object. when I send request to API , it shows me empty lists while rest of the data is in place. while debugging I came to know that before returning to API controller my service object has all the data expected i.e lists has data , but when it comes back to web API the lists are empty.
After searching for solution over web I came to know that every time a request is to the API the lists are recreated , so it shows empty result. Any Solutions to come out of this problem?
Here is my piece of code.
The following Is the Web Api Method.
[HttpGet()]
[Route("edit/{readingListId}")]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetReadingListById(int readingListId)
{
try
{
var readingList = await this._readingListService.GetReadingListByIdAsync(readingListId);
return Ok(readingList);
}
catch (Exception ex)
{
this._logger.LogError(ex.Message);
return BadRequest();
}
}
The following Is the Service Method.
public async Task<Domain.ReadingList> GetReadingListByIdAsync(int readingListId)
{
try
{
Domain.ReadingList readingList = await _repository.FindById(readingListId);
return readingList;
}
catch (Exception ex)
{
throw;
}
}
Moreover , This Is My Entity.
public class ReadingList : EntityBase, IAggregateRoot, IAggregateCreateRoot, IAggergateUpdateRoot, IAggregateDeleteRoot
{
public ReadingList()
{
this.Items = new List<ReadingListItem>();
this.Assignees = new List<ReadingListAssignee>();
}
public int Id { get; set; }
public EntityType EntityTypeId { get; set; }
public int EntityId { get; set; }
public string Title { get; set; }
public DateTime CompletionDate { get; set; }
public int ReminderDay { get; set; }
public string ReminderDayType { get; set; }
public bool SendReminder { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public int? DeletedBy { get; set; }
public DateTime? DeletedDate { get; set; }
public bool? Deleted { get; set; }
public List<ReadingListItem> Items { get; private set; }
public List<ReadingListAssignee> Assignees { get; private set; }
}
Thanks!
Edited
The Issue Was Resolved , By Simply Changing The dll Versions.One Of The Service Had And Old Version While The Version Was Updated In The Other One.
Thanks For The Help.

Parameter from angular not mapped into C# object

I have a problem with mapping one parameter from my angular $http call to C# method.
On a server side I use MVC. On a client is angular. I've tried to debug with developer tools inside Chrome and everything was fine, without errors.
Parameter which doesn't map (stays null) is cORAM_NTO. I've checked in console that $scope.Note is filled with value.
But, on the server side value for cORAM_NTO is null.
Here is call on client side (angular):
$scope.SaveModal = function (event)
{
$http(
{
method: "POST",
url: $scope.UrlSaveDataCAORAM,
data:
{
iORAM_KEY: $scope.CurrentORAM_KEY,
dORAM_DSE: $scope.SellDate,
cORAM_MPA: $scope.WayPayment,
cORAM_NIC: $scope.ConfirmationNumber,
cORAM_ANB: $scope.AccountNumber,
dORAM_DBE: $scope.DateUse,
decORAM_VAU: $scope.AmountUse,
cORAM_ANB2: $scope.AccountAmountUseRest,
dORAM_DBE2: $scope.DateUseRest,
decORAM_VAU2: $scope.AmountUseRest,
cORAM_NTO: $scope.Note
}
}).then(function success(response)
{
}, function failure()
{
})
}
Here is class for DTO_CAORAM (parameter cORAM_NTO is last):
public class DTO_CAORAM
{
public int? iORAM_KEY { get; set; }
public int? iORAS_KEY { get; set; }
public int? iMEST_KEY { get; set; }
public int? iUNIT_KEY { get; set; }
public string cORAM_SRT { get; set; }
public string cORAM_STA { get; set; }
public DateTime? dORAM_DAT { get; set; }
public double? decORAM_QUA { get; set; }
public string cORAM_UNI { get; set; }
public double? decORAM_NET { get; set; }
public double? decORAM_GRO { get; set; }
public DateTime? dORAM_DSE { get; set; }
public string cORAM_MPA { get; set; }
public string cORAM_NIC { get; set; }
public string cORAM_ANB { get; set; }
public DateTime? dORAM_DBE { get; set; }
public double? decORAM_VAU { get; set; }
public string cORAM_ANB2 { get; set; }
public DateTime? dORAM_DBE2 { get; set; }
public double? decORAM_VAU2 { get; set; }
public string cMEST_CDO2 { get; set; }
public int? iMERC_KEY { get; set; }
public int? iACCO_KEY { get; set; }
public int? iORAC_KEY { get; set; }
public string cORAM_NTO { get; set; }
}
And finally function on server side (all params are mapped except cORAM_NTO):
public void SaveDataCAORAM(DTO_CAORAM dto)
{
}
Here is POST request recorded from a network tab:
dto
:
{iORAM_KEY: "160000008", dORAM_DSE: "01.06.2016", cORAM_MPA: "fsfsfsdf", cORAM_NIC: "6666",…}
cORAM_ANB
:
"jjjgfhgfhg"
cORAM_ANB2
:
"rtttttt"
cORAM_MPA
:
"fsfsfsdf"
cORAM_NIC
:
"6666"
cORAM_NTO
:
"notest test"
dORAM_DBE
:
"02.07.2016"
dORAM_DBE2
:
"03.08.2016"
dORAM_DSE
:
"01.06.2016"
decORAM_VAU
:
"54444,0000"
decORAM_VAU2
:
"7777,0000"
iORAM_KEY
:
"160000008"
I've renamed parameter cORAM_NTO to cORAM_NTO1 and tried that. It worked. Than I renamed it back and it worked with cORAM_NTO.

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