Breezejs entity, knockout binding, null navigation properties - javascript

I know I am doing something stupid here but I'm hoping someone with some Breezejs experience can help me out (please) as I am new to it. So the problem is when I do a breeze manager.saveChanges() the navigation properties (and only the navigation properties) are not sent to the server. In my model all the navigation properties are just lookup items if that makes any difference and I am using knockout to do the binding. Here is a screenshot to show whats wrong:-
the relevant bit in my dataservice just does this:-
function createAssessment() {
return manager.createEntity('VulnerabilityAssessment');
}
Domain model:-
public class VulnerabilityAssessment
{
public int Id { get; set; }
public virtual AssessmentStatus Status { get; set; }
public virtual PupilRecord Pupil { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string LatestContact { get; set; }
public string Referrer { get; set; }
public virtual ReferralReason ReasonForReferral { get; set; }
public string SingleResponsibleAdult { get; set; }
public string CurrentIssues { get; set; }
public virtual ReferralSupport PrimaryReferralSupport { get; set; }
public virtual ReferralSupport SecondaryReferralSupport { get; set; }
public bool LikelyToLeaveWithoutQualification { get; set; }
public virtual Destination MovingOnDestination { get; set; }
public virtual Destination DestinationAfterOneMonth { get; set; }
public virtual Destination DestinationAfterSixMonths { get; set; }
public virtual Destination DestinationAfterTwelveMonths { get; set; }
public virtual ProtectedCharacteristic ProtectedCharacteristic { get; set; }
public string Undisclosed { get; set; }
}
Here is my viewmodel:-
define(['services/logger', 'services/dataservice'], function (logger, dataservice) {
var title = 'Vulnerability Assessment';
this.activate = function activate() {
var initialData = dataservice.getAssessmentLookups()
.then(function (data) {
vm.referralReasonCodes(data.referralReasonCodes);
vm.referralSupportCodes(data.referralSupportCodes);
vm.assessmentStatusCodes(data.assessmentStatusCodes);
vm.destinations(data.destinations);
vm.protectedCharacteristics(data.protectedCharacteristics);
vm.assessment(dataservice.createAssessment());
console.log('assessment: %A', vm.assessment());
})
.done();
logger.log(title, null, title, true);
return initialData;
}
this.save = function () {
console.log('in save: %A', vm.assessment());
dataservice.saveChanges();
}
var vm = {
activate: this.activate,
title: title,
referralReasonCodes: ko.observableArray(),
referralSupportCodes: ko.observableArray(),
assessmentStatusCodes: ko.observableArray(),
destinations: ko.observableArray(),
protectedCharacteristics: ko.observableArray(),
assessment: ko.observable(),
save: this.save
};
return vm;
});
View/HTML:-
<select id="reason-for-referral" class="form-control input-md" data-bind="options: $root.referralReasonCodes, optionsText: 'description', value: $data.reasonForReferral"></select>
Note: the select element above is within a another div that goes like this:-
<div class="row" data-bind="with: assessment">
Here is a look at my object just before it is sent to the server.
Totally stuck at the moment...
Many thanks for taking a look.

Breeze does not send "related" entities ( those available thru navigation properties) in a save UNLESS these related entities are "modified", "added" or "deleted". This is the default behavior when you call EntityManager.saveChanges without any parameters. The reason for this is that we don't want send any data that has not actually changed.
If, on the other hand, you are calling EntityManager.saveChanges and passing in a list of entities then you will need to include any related entities that you want send to the server as part of the list.
If not, then why do you want to send entities that have not changed to the server on a "saveChanges" call? Am I missing something?

Related

How to display a line follower of a service processes using ASP.Net MVC

Please, I need to know how can I make similar to this table in MVC .. my data come from a model as a list of services, each service has a process from a list also, so I need to display a table of the service details and each detail linked to one process at time .. so the sequence of the processes display a line of similar to line chart.. Thank you in advance
I attached a picture though to show what I meant exactly.
Model:
public partial class ServiceDetail
{
public int ServiceDetailsID { get; set; }
public string ServiceDetailDescription { get; set; }
public int ServiceSequence { get; set; }
public System.TimeSpan TimeToComplete { get; set; }
public int ServiceID { get; set; }
public int ProcessID { get; set; }
public virtual Process Process { get; set; }
public virtual Service Service { get; set; }
}
public partial class Process
{
public Process()
{
this.ServiceDetails = new HashSet<ServiceDetail>();
}
public int ProcessID { get; set; }
public string ProcessName { get; set; }
public virtual ICollection<ServiceDetail> ServiceDetails { get; set; }
}
Controller:
public ActionResult Display(int? id) // Service's ID passed from another property
{
var serviceDetails = db.ServiceDetails.Where(x => x.ServiceID == id).ToList();
return View(serviceDetails);
}

How to pass an array in formData

I am using formData and trying to pass an array that receives it in .Net Core backend
this is my array that i try to send truck.StateTruck:
{
0: {StaId: 6}
1: {StaId: 7}
2: {StaId: 8}
3: {StaId: 9}
}
this is my method to send my data that I try to send only the StaId and its value:
let formData = new FormData();
formData.set('DriId',truck.DriId);
formData.set('TruExdate',truck.TruExdate);
formData.set('TruAddress',truck.TruAddress);
formData.set('TruCity',truck.TruCity);
formData.set('TraId',truck.TraId);
formData.set('TruZip',truck.TruZip);
formData.set('TruYear',truck.TruYear);
formData.set('TruMake',truck.TruMake);
formData.set('TruType',truck.TruType);
formData.set('TruFuel',truck.TruFuel);
formData.set('TruAxles',truck.TruAxles);
formData.set('TruVin',truck.TruVin);
formData.set('TruDocurl',truck.TruDocurl);
formData.set('TraUnit',truck.TraUnit);
formData.set('TraMake',truck.TraMake);
formData.set('TraYear',truck.TraYear);
formData.set('TtyId',truck.TtyId);
formData.set('TraIntmaterial',truck.TraIntmaterial);
formData.set('TraEquipament',truck.TraEquipament);
formData.set('TraOption',truck.TraOption);
formData.set('Fichero',truck.Fichero);
formData.append('StateTruck',JSON.stringify(truck.StateTruck));
when printing to the console using the console.log (formData.getAll ('StateTruck')); I see
["[{"StaId":6},{"StaId":7},{"StaId":8},{"StaId":9}]"]
and my backend expects this structure:
public class TruckRequest
{
public int TruId { get; set; }
public int? DriId { get; set; }
public DateTime? TruExdate { get; set; }
public string TruAddress { get; set; }
public string TruCity { get; set; }
public int? TraId { get; set; }
public string TruZip { get; set; }
public string TruYear { get; set; }
public string TruMake { get; set; }
public string TruType { get; set; }
public string TruFuel { get; set; }
public string TruAxles { get; set; }
public string TruVin { get; set; }
public string TruDocurl { get; set; }
public string TraUnit { get; set; }
public string TraMake { get; set; }
public string TraYear { get; set; }
public int? TtyId { get; set; }
public string TraIntmaterial { get; set; }
public string TraEquipament { get; set; }
public string TraOption { get; set; }
public IFormFile Fichero { get; set; }
public string TruUregistro { get; set; }
public DateTime? TruUfecha { get; set; }
public string TruUupdate { get; set; }
public DateTime? TruUupdatefecha { get; set; }
public string TruEstado { get; set; }
public virtual ICollection<StateTruck> StateTruck { get; set; }
}
public partial class StateTruck
{
public int SruId { get; set; }
public int? StaId { get; set; }
public string SruUregistro { get; set; }
public DateTime? SruUfecha { get; set; }
public string SruUupdate { get; set; }
public DateTime? SruUupdatefecha { get; set; }
public string SruEstado { get; set; }
public int? TruId { get; set; }
}
How can I give it the correct format so that it can be received?
if you need the value converted to string, you may use
e.g.
formData.set('TruYear', truck.TruYear.toString());
for integer, e.g.
formData.set('TruYear', parseInt(truck.TruYear));
All these are passed as formData to your backend, your server should create the parser to convert to the right format, and to validate it is the right format.
Never, trust, anything submitted from frontend.
When console logging out the data you need to parse the first element in the array received from formData.getAll ('StateTruck'). The following should help in your scenario:
console.log(JSON.parse(formData.getAll("StateTruck")[0]))
According to your description, I assume you want to use FormData to pass value (include the object array) from client side to server side (Web API). If that is the case, you could refer to the following sample code:
Client side (using JQuery Ajax to call the web API method):
$(function () {
//Submit Main Form.
$("#btnCreate").click(function (event) {
//Prevent Default Region.
event.preventDefault();
//define an array to store the StateTruck
var statetruce = new Array();
for (var i = 0; i < 5; i++) {
statetruce.push({ StaId: i });
}
let formData = new FormData();
formData.set('DriId', 101);
formData.set('TruAddress', "Address 1");
formData.set('TruCity', "city A");
formData.set('TraId', 1011);
formData.set('TruZip', "zip12");
formData.set('TruYear', "years ");
formData.append('StateTruck', JSON.stringify(statetruce));
$.ajax({
url: '/api/TestAPI',
type: "post",
async: true,
data: formData,
processData: false,
contentType: false,
success: function (response) {
// window.location.href = response;
}
});
});
});
Based on the Array Object's property to create a View Model, it is used to Deserialize the array object.
Code in the Web API method:
[HttpPost]
public async Task<IActionResult> Post(IFormCollection collection)
{
var DriId = collection["DriId"].ToString();
var TruAddress = collection["TruAddress"].ToString();
var StateTruck = collection["StateTruck"].ToString();
//deserialize the object
var result = System.Text.Json.JsonSerializer.Deserialize<List<StateTruckViewModel>>(StateTruck);
//do something
return Ok("success");
}
Then debug screenshot as below:

mvc controller is passing in null from javascript object that has data

I have an MVC controller that somehow is passing in Null to it
Controller:
[HttpPost]
public ActionResult UpdateAllNodes(IEnumerable<ReportGroup> reportGroups)
{
// this is custom return..
return JsonCamel(null);
}
PROBLEM : reportGroups is null
javascript ajax post
$.post(updateAllNodeUri, JSON.stringify({ reportGroups: homogeneous.data() }));
Chrome Dev Tools Form Data:
{"reportGroups":[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]}:
So I have the reportGroups in controller along with the JSON as reportGroups: thus I'm lost on why it is null.
Also here here the poco class for the ReportGroup
public class ReportGroup : BaseEntity
{
public override int Id { get; set; }
public string ReportGroupName { get; set; }
public int? ReportGroupNameResID { get; set; }
public int SortOrder { get; set; }
}
Kendo data calls , then I can output to console and see the data as well
console.log(homogeneous.data());
// ### Send the Data to the server
var updateAllNodeUri = "/Report/UpdateAllNodes";
Based on the JSON data you get from Chrome Dev Tools, you are actually sending the JSON with this model:
JSON:
{"reportGroups":[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]}:
Model:
public class ReportGroup
{
public int Id { get; set; }
public string ReportGroupName { get; set; }
public object ReportGroupNameResID { get; set; }
public int SortOrder { get; set; }
public List<object> items { get; set; }
public int index { get; set; }
}
public class RootObject
{
public List<ReportGroup> reportGroups { get; set; }
}
The RootObject class is the one being received by your controller which is not the expected parameter.
Try transforming the JSON to this format:
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]
Javascript:
$.post(updateAllNodeUri, JSON.stringify(homogeneous.data()));

Insert "Multiple Field Value" in the Same Column in MVC4?

I want to save the Multiple field Values in the same Column.
TaxField Table contain 3 Fields
1)TaxFieldID
2)DisplayName
3)PrintName
TaxFieldID = FD713788-B5AE-49FF-8B2C-F311B9CB0CC4
DisplayName = TinNo
PrintName = TinNo
The value of TinNo CinNo etc all are have default value which is saved in TaxField Table
TaxInfoTaxField Table
My View contain six fields TinNo, CstNo, PanNo, ServiceTaxNo,ExciseRegNo, CinNo.
Format to save the Value and ID in TaxInfoTaxFieldTable
TinNo = FD713788-B5AE-49FF-8B2C-F311B9CB0CC4
CstNo = 64B512E7-46AE-4989-A049-A446118099C4
CinNo =59A2449A-C5C6-45B5-AA00-F535D83AD48B
My Model
public partial class TaxInfoTaxFiled
{
public System.Guid TaxInfoTaxFieldID { get; set; }
public Nullable TaxInfoID { get; set; }
public Nullable TaxFieldID { get; set; }
public Nullable FieldTypeID { get; set; }
public string FieldValue { get; set; }
}
public partial class TaxField
{
public System.Guid TaxFieldID { get; set; }
public string DisplayName { get; set; }
public string PrintName { get; set; }
}
MyViewModel
public class TaxViewModel1
{
public System.Guid TaxInfoTaxFieldID { get; set; }
public System.Guid TaxInfoID { get; set; }
public Nullable TaxFiledID { get; set; }
public string TinNo { get; set; }
public string CstNo { get; set; }
public string ExciseRegNo { get; set; }
public string PanNo { get; set; }
public string ServiceTaxNo { get; set; }
public string CinNo { get; set; }
}
public class VisitorsEntities1 : DbContext
{
public DbSet TaxField { get; set; }
public DbSet TaxInfo { get; set; }
public DbSet TaxInfoTaxFiled { get; set; }
}
My Controller
[HttpPost]
public ActionResult Index(TaxViewModel1 TVM)
{
Type type = typeof(TaxField);
PropertyInfo[] Info = new
TaxInfoTaxField().GetType().GetProperties();
foreach (TaxInfoTaxField property in properties)
{
var Value = property.GetValue(TVM.TinNo, null);
var Value1 = property.GetValue(TVM.CstNo, null);
}
return View(Tax);
}
Sir In this below Code we pass the Properties of TaxField and it is get by TaxinfoTaxField Table
Type type = typeof(TaxField);
PropertyInfo[] Info = new TaxInfoTaxField().GetType().GetProperties();
And in 'foreach Loop ' we assigning the Value to the Variable. But how to assign the value to the Column .And How to do save the Value in FieldValue and ID in TaxFieldID of TaxInfoTaxField Table in the above format which I mentioned. Please Correct my Controller Code . I am very very new to MVC . so only I struggling for this Small Concepts. Please correct my Controller Code and help me to save the Values in the TaxInfoTaxField table. And if you have a times means please explain me the Logic used in Controller.
Thanks.

Nested JSON values not binding MVC

I have a game object in client side JavaScript that looks like this right before being sent to the server:
Here it is server side a second later, note all the properties are filled, and the Questions list is populated with the correct number of question, however the properties of each question are null, whereas on the client side they had the correct values.
Here is the code for the models:
public class Game
{
public Game()
{
Questions = new List<Question>(5);
}
public int GameID { get; set; }
public Guid UserID { get; set; }
public Guid CurrentGameID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<Question> Questions { get; set; }
}
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public IEnumerable<int> Answers { get; set; }
public int SelectedAnswer { get; set; }
}
And here is how I send the object back to the server:
// Send completed game back to server
$.post("Games/CompleteGame", currentGame, function (results)
{
// display results to user
}
Based on Ek0nomik's comment asking about the content-type, I rewrote my ajax call to set contentType to json:
$.ajax(
{
url: "Games/CompleteGame",
type: "POST",
data: JSON.stringify(currentGame),
contentType: "application/json",
success: function (results)
{
// show results to user...
}
As it turns out, this was all it needed to make it work.

Categories