Translate boolean to bool after Ajax call - javascript

Hi,
I have a .net class that contains a Boolean, this class is sent to client with AJAX. The problem is that if I just use :
if(MyClass.CheckedValue)
It will always be true even if the CheckedValue is false. I supose that it is instead checking if the object is set and if so it is true? Im note sure what type this Boolean propertie gets when returning to the javascript after AJAX?
I have also tried this :
var checked;
checked = Boolean(this.CheckedValue === 'true');
if (checked)
But this will also laways be true?
How do I handle this?
Edit1 :
The classes that is sent to client :
/// <summary>
/// Are set to client with Ajax to render a correct view of the
/// current category and filter settings
/// </summary>
public class GetCategoriesAndFiltersAjax
{
public GetCategoriesAndFiltersAjax()
{
Filters = new Filter();
}
public SelectList categoryList { get; set; }
public Filter Filters { get; set; }
public class Filter
{
public Filter()
{
DefaultFilters = new List<CategoryItemFilter>();
FilterList = new List<CategoryItemFilter>();
}
/// <summary>
/// Filters like buy, sell, let and so on
/// </summary>
public List<CategoryItemFilter> DefaultFilters { get; set; }
/// <summary>
/// All other filters that a category might be bound to
/// </summary>
public List<CategoryItemFilter> FilterList { get; set; }
}
}
public class CategoryItemFilter
{
private int _filterId = -1;
private string _clientElementId1;
private string _clientElementId2;
public FilterControlType FilterControlType { get; set; }
public string Title1 { get; set; }
public string Title2 { get; set; }
public string ClientElementId1
{
get { return _clientElementId1; }
set
{
_clientElementId1 = value;
}
}
public string ClientElementId2
{
get { return _clientElementId2; }
set
{
_clientElementId2 = value;
}
}
/// <summary>
/// Keep track of whitch filter it is
/// </summary>
public int FilterId
{
get { return _filterId; }
set { _filterId = value; }
}
#region Values
public Boolean CheckedValue { get; set; }
public string TextValue { get; set; }
public SelectList DropDownList1 { get; set; }
public SelectList DropDownList2 { get; set; }
#endregion
public PublicAdFilterKey PublicAdFilterKey { get; set; }
}
And this is how the AJAX method looks like on server :
public JsonResult GetCategoriesByParent(int id, Boolean editMode)
{
FilterModel filterModel = new FilterModel();
CategoryModel categoryModel = new CategoryModel();
List<ModelViewCategory> mvCategoryList = new List<ModelViewCategory>();
//List<AdCategory> categoryList;
FilterHandler filterHandler = new FilterHandler();
GetCategoriesAndFiltersAjax value = new GetCategoriesAndFiltersAjax();
try
{
value.categoryList = new SelectList(categoryModel.GetCategoriesByParent(id).ToArray(), "Id", "Name");
if (editMode)
value.Filters = filterHandler.ConvertFilterModelToAjaxCategoryFilter(filterModel.GetCategoryFilterByCategory(id), Biss.Views.ViewClasses.Filter.FilterType.Edit);
else
value.Filters = filterHandler.ConvertFilterModelToAjaxCategoryFilter(filterModel.GetCategoryFilterByCategory(id), Biss.Views.ViewClasses.Filter.FilterType.Display);
return this.Json(value, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw;
}
}
Edit 2 :
This is how the client looks like(not exacly but close, its alot more complicated)
$.ajax({
url: actionPath,
type: 'POST',
dataType: 'json',
data: ((typeof config.postData == "function") ? config.postData() : config.postData) || { id: $(source).val(), editMode: _filterInEditMode },
success: function (data) {
methods.reset();
$.each(data.categoryList, function () {
SetFilterSubEdit(data.DefaultFilters);
},
error: function () {
methods.showError();
}
});
function SetFilterSubEdit(data) {
$.each(data, function () {
if (data.CheckedValue)
$("#" + visibleElements[0]).attr('checked', checked);
}
}

Sorry, the problem was that the brackets was missing on client side.
if (data.CheckedValue){
}

Related

MVC core 5.0 update js via Viewmodel

im trying to update data in javascript via viewmodel.
When the side loads it works.
window.addEventListener('load', function () {
let listModel = #Html.Raw(Json.Serialize(Model));
LoadAllInfoSpots(listModel);
});
But when i call my js function
function afterClickOnFlorplan() {
setTimeout(function () {
let listModel =#Html.Raw(Json.Serialize(Model));
LoadAllInfoSpots(listModel);
}, 1500);
}
the let listmodel is the same as when i loaded the side. with a count of 4.
i know the viewmodel is updating.
but as you can see let listmodel is not updated in my js code.
So why is the let listmodel the same all the time?
hope you can help me.
Model:
public class SelectorModel
{
public int? ID { get; set; }
public string ImageName { get; set; }
public string Cords { get; set; }
public string Name { get; set; }
}
ViewModel:
public class SelectorViewModel
{
public List<SelectorModel> SelectorModels { get; set; }
}
the first IActionResult:
public IActionResult Index()
{
LoadInfoSpotsFromDB load = new LoadInfoSpotsFromDB();
string first = load.LoadFirstImage();
SetFirstIMageCookie(first);
List<SelectorModel> loaede = load.Load(first);
selectorViewModel = new SelectorViewModel
{
SelectorModels = loaede
};
return View(selectorViewModel);
}
the IActionResult that update the ViewModel
[HttpPost]
public IActionResult Index([FromBody] string dontremove)
{
selectorViewModel = null;
LoadInfoSpotsFromDB load = new LoadInfoSpotsFromDB();
List<SelectorModel> loaede = load.Load(HttpContext.Request.Cookies["ImageName"]);
selectorViewModel = new SelectorViewModel
{
SelectorModels = loaede
};
return View(selectorViewModel);
}

Passing a list from angular to c# through http request

My method in c# receives a list as a parameter, I am trying to call this method in angular by passing it an array, but the problem is that the info doesn't reach the c# method, the list is always empty, even though there was information in the angular array.
export class StationAllocationPostModel{
idAppDeviceOwnerEntity: number;
idAppDeviceOwnerEntityOriginal: number;
idAppDeviceOwnerEntityRentalLocationId: number;
Observations: string;
selectedAppDevices: StationAllocationModel[];
}
createNewStationAllocation(selectedAppDevices: StationAllocationPostModel){
return this.post("home/CreateAppDeviceRentalLocationAllocation", selectedAppDevices, {
params: {
'idAppDeviceOwnerEntity': selectedAppDevices.idAppDeviceOwnerEntity,
'idAppDeviceOwnerEntityRentalLocationId': selectedAppDevices.idAppDeviceOwnerEntityRentalLocationId,
'Observations': selectedAppDevices.Observations,
'selectedAppDevices': selectedAppDevices.selectedAppDevices
}
});
}
public post(url: string, data: any, options = null) {
return new Promise<any>((resolve, reject) => {
let response;
this.http.post(
this.baseUrl + url,
{
data: data
},
{
headers: options ? options.headers : null,
observe: options ? options.observe : null,
params: options ? options.params : null,
reportProgress: options ? options.reportProgress : null,
responseType: options ? options.responseType : null,
withCredentials: options ? options.withCredentials : null
}
)
.subscribe(
data => {
response = data;
if (response && !response.success) {
if (response.response.ServerResponse[0].MessageType == "NOSESSIONEXCEPTION") {
localStorage.removeItem('userSession');
this.router.navigate(['/login'], { queryParams: { returnUrl: this.router.url } });
}
}
},
error => {
resolve(null);
this.handleError(url, options ? options.params : null );
console.log(error);
}, () => {
if (response) {
resolve(response);
} else {
resolve(null);
}
}
);
})
}
This is my c# method:
public Object CreateAppDeviceRentalLocationAllocation(<other params>, List<AppDeviceRentalLocationAllocationHistoryExtended> selectedAppDevices)
{
...
}
I am expecting that the c# method receives a list with elements, but it always comes out empty for some reason. The 'other params' are getting the right information, so I don't know what's wrong with the list.
Sorry for the long post, I'm new here.
Could you please form a param object on the C# method that holds the following :
public class SelectedAppDevice
{
public int idAppDevice { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public string Observations { get; set; }
public string DeviceId { get; set; }
public string EntityRentalLocationName { get; set; }
public DateTime CreationDate { get; set; }
public DateTime EndDate { get; set; }
public string CreatedByUserName { get; set; }
public int RentalStatus { get; set; }
public int idAppDeviceRental { get; set; }
public bool IsRentalStart { get; set; }
public bool IsRentalEnd { get; set; }
public object idNextExpectedEntityRentalLocationName { get; set; }
public object NextExpectedEntityRentalLocationName { get; set; }
public string LastKnownEntityRentingId { get; set; }
public string CallerId { get; set; }
public int RentalStatusId { get; set; }
public int DeviceStatusId { get; set; }
}
public class Data
{
public string Observations { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public List<SelectedAppDevice> selectedAppDevices { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
and make it as a controller method parameter :
public Object CreateAppDeviceRentalLocationAllocation(RootObject param)
{
...
}

KendoUI treeview children are displayed as undefined

I have a treeview in kendoUI in which main nodes are calling into an mvc controller and that controller looks to whether there is an nullable id passed in and then uses a different model.
What I hit the url : http://localhost:2949/Report/GetReportGroupAssignments
I see this JSON
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4}
]
Now my mvc controller looks like this
public JsonResult GetReportGroupAssignments(int? id)
{
var model = new List<ReportGroup>();
var defModel = new List<ReportDefinition>();
try
{
if (id == null)
{
model = _reportService.GetReportGroups("en-us").ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
else
{
defModel = _reportService.GetReportDefinitions().Where(e=>e.ReportGroupID ==Convert.ToInt32(id)).ToList();
return Json(defModel, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Logger.Error(ex, "Error loading LoadReportList.");
return null;
}
}
My Kendo javascript looks like the following:
var serviceRoot = "/Report"; // "//demos.telerik.com/kendo-ui/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments", //"/LoadReportTree", // "/Employees",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,hasChildren: "Id"
}
}
});
var treeview = $("#treeview").kendoTreeView({
expanded: true,
dragAndDrop: true,
dataSource: homogeneous,
dataTextField: "ReportGroupName"
}).data("kendoTreeView");
Seems that the calls (which I discovered that children records have a "load" method that it called behind the seens, so basically I pass in the ID in order to get the data from the other model ( table in db)
(Id is mapped with automapper to ReportGroupID )
So when i click to the left of "Standard Rports" I am getting all of these children as undefined, How do I get these to show up properly?
Update: My ReportDefinition class:
public class ReportDefinition {
public override int Id { get; set; }
public string ReportKey { get; set; }
public string ReportName { get; set; }
public int? ReportNameResID { get; set; }
public string ReportDef { get; set; }
public int? ReportDefinitionResID { get; set; }
public string ReportAssembly { get; set; }
public string ReportClass { get; set; }
public int ReportGroupID { get; set; }
public int AppID { get; set; }
public int SortOrder { get; set; }
public bool IsSubReport { get; set; }
}
I think your problem is that the class ReportDefinition does not have a property called: ReportGroupName. That is why TreeView displays 'undefined'.
Try adding this Property to your ReportDefinition class like:
public class ReportDefinition {
// Other Properties
// I guess this property is missing
public string ReportGroupName { get; set; }
}

pass JsonResult object from javascript function in View to Controller

How can I pass JsonResult object from javascript function in View to Controller Action without Ajax call - just javascript - window.location.href = url?
I get JsonResult object from Controller Action to javascript function via Ajax call. Then I want to pass this object back to other Controller Action but I get object with null reference properties.
My javascript function in View:
function order(model) {
$('#details-container').html("<h2>Loading Complete Frame Module. Please wait...</h2>");
$.p({
url: '#Url.Action("CompleteFrameBrandDetails", "PacCompleteFrame")',
data: { item: model },
success: function (xml) {
if (xml.Success) {
$.p({
url: '#Url.Action("GlassCompleteFrame", "PacModule")',
data: JSON.stringify({ b2bXml: xml.Data }),
success: function (model) {
var pacModuleModel = {
Mode: model.Data.Mode,
IframeUrl: model.Data.IframeUrl.toString(),
CustomerNumber: model.Data.CustomerNumber.toString(),
ReadOnly: model.Data.ReadOnly,
GlassXml: model.Data.GlassXml.toString(),
Price: parseFloat(model.Data.Price),
Comission: model.Data.Comission.toString(),
Permissions: null,
Language: model.Data.Language.toString()
};
// here are all values in model.Data correct
// but then I can't figure out how to pass it to Controller Action without Ajax call - just with javascript command
var url = '#Url.Action("GlassCompleteFrameView", "PacModule", "__view__")';
window.location.href = url.replace("__view__", model.Data); //pacModuleModel
}
});
} else {
$.alert({
message: 'error while trying to load xml details'
});
}
}
});
}
My Controller Action:
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return View("Glass", model);
}
I have also Model like this for automatic Json binding but dont work:
public enum ModuleMode
{
ByProduct,
ByRecipe
}
public partial class PacModuleModel
{
private PacPermissionModel permissionModel;
public ModuleMode Mode { get; set; }
public string IframeUrl { get; set; }
public string CustomerNumber { get; set; }
public bool ReadOnly { get; set; }
public string GlassXml { get; set; }
public double? Price { get; set; }
public string Comission { get; set; }
public PacPermissionModel Permissions
{
get
{
if (permissionModel == null)
{
permissionModel = new PacPermissionModel();
}
return permissionModel;
}
}
public string Language { get; set; }
}
Try this in controller
public JsonResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return Json(model, JsonRequestBehavior.AllowGet);
}
The problem was in model. It was more than 45000 char long. Now I use Session variable to get model in GlassCompleteFrameView(PacModuleModel model) and works perfect.
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
model = Session["xml"] as PacModuleModel;
return View("Glass", model);
}

Breeze.js /NET+EF complex object behaviors rather strange

I’m developing a custom data access layer to be consumed in breeze.js
What I have:
The Model:
public class Product
{
[Key]
public int ProductId { get; set; }
public string Upc { get; set; }
public string Name { get; set; }
public decimal MsrpPrice { get; set; }
public int Quantity { get; set; }
public virtual ICollection<ProductFeature> Features { get; set; }
public virtual B2BCategory InB2BCategory { get; set; }
public virtual ICollection<ImageDescriptor> Images { get; set; }
public int CategoryId {get; set;}
}
public class ProductFeature
{
public int ProductId { get; set; }
public string Name { get; set; }
public string GroupName { get; set; }
public string Operation { get; set; }
public decimal Value { get; set; }
}
public class ImageDescriptor
{
public int ProductId { get; set; }
public string Uri { get; set; }
public DateTime Updated { get; set; }
public bool IsDefault { get; set; }
}
The Context Provider:
public class ProductContextProvider : ContextProvider
{
private readonly ProductRepository repo =new ProductRepository();
public IQueryable<B2BCategory> Categories
{
get { return repo.Categories.AsQueryable(); }
}
public IQueryable<Product> Products
{
get
{
return repo.Products.OrderBy(p => p.ProductId).AsQueryable();
}
}
protected override string BuildJsonMetadata()
{
var contextProvider = new EFContextProvider<ProductMetadataContext>();
return contextProvider.Metadata();
}
protected override void SaveChangesCore(SaveWorkState saveWorkState)
{…
}
// No DbConnections needed
public override IDbConnection GetDbConnection()
{
return null;
}
protected override void OpenDbConnection()
{
// do nothing
}
protected override void CloseDbConnection()
{
// do nothing
}
}
internal class ProductMetadataContext : DbContext
{
static ProductMetadataContext()
{
Database.SetInitializer<ProductMetadataContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProductFeatureConfiguration());
modelBuilder.Configurations.Add(new ImageDescriptorConfiguration());
}
public DbSet<Product> Products { get; set; }
public DbSet<B2BCategory> Categories { get; set; }
}
internal class ImageDescriptorConfiguration : EntityTypeConfiguration<ImageDescriptor>
{
public ImageDescriptorConfiguration()
{
// I tried to mess up with key orders
HasKey(i => new { i.Uri, i.ProductId});
}
}
internal class ProductFeatureConfiguration : EntityTypeConfiguration<ProductFeature>
{
public ProductFeatureConfiguration()
{
HasKey(f => new { f.ProductId, f.Name });
}
}
I’m stuffing the Features and Images properties of a Product directly:
product.Features = new Collection<ProductFeature>();
product.Images = new Collection<ImageDescriptor>();
…
var imgd = new ImageDescriptor
{
ProductId = product.ProductId,
Updated = DateTime.Now,
Uri = defsmall,
IsDefault = !product.Images.Any()
}
product.Images.Add(imgd);
…
var pf = new ProductFeature
{
ProductId = product.ProductId,
GroupName = "Size",
Name = size,
Value = size == "Small" ? new decimal(.75):size == "Medium" ? new decimal(1.3):new decimal(1.8),
Operation = "*"
};
product.Features.Add(pf);
Totally there are, say, 3 product features and 2 images per product item.
In the client side I query this like:
return entityQuery.from('Products').using(EntityManager).execute();
And… I’ve got the very strange thing:
The images property contains an empty array, the features property contains an array of 5!!! elements – 3 of type ProductFeature and 2 of type ImageDescriptor.
I think this is a bug – could you help me, please?
I don't see any code that creates a breeze EntityManager and adds or attaches your newly created entities and then saves them. Please take a look at the Breeze examples in the downloadable zip from the BreezeJs website.

Categories

Resources