MVC core 5.0 update js via Viewmodel - javascript

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

Related

Build a view model for c# using jQuery

I have one view model and i'm pass that view model into controller, but one of the model property is a list of other class. so i'm not able to bind it via jQuery.
I have the following view model.
public class ToolsAddViewModel
{
public string Tools_Name { get; set; }
public string Tools_Desc { get; set; }
public int Category_ID { get; set; }
public List<ToolsParamsBlockViewModel> Params_List { get; set; }
}
ToolsParamsBlockViewModel class that is used as list type
public class ToolsParamsBlockViewModel
{
public int Params_ID { get; set; }
public string Params_CSS_Attribute { get; set; }
public int Params_Priority { get; set; }
}
here is my controller method that handle viewmodel data
[HttpPost]
public ActionResult Manage(ToolsAddViewModel toolsAddViewModel)
{
//insert viewmodel data into database
return RedirectToAction("Index", "Tools");
}
and finally im trying to add data into viewmodel using jQuery, here it is. im use table for add list into Params_List property.
$("#btnSave").on("click", function () {
var ParamsList = [];
$('#paramsBlockTable tbody > tr').each(function () {
var SingleParams = [];
$(this).find("input,select").each(function () {
SingleParams.push($(this).val());
console.log(values);
});
ParamsList.push(values);
});
var ToolsModel = {
"ID": $("#ID").val(),
"Tools_Name": $("#Tools_Name").val(),
"Category_ID": $("#Category_ID").val(),
"Params_List": ParamsList,
"ScriptFiles_IDs": $("#ScriptFiles_IDs").val(),
"Tools_SEO_Keyword": $("#Tools_SEO_Keyword").val(),
"Tools_Desc": $("#Tools_Desc").val(),
}
console.log(ToolsModel);
});
here in ParamsList have array of table row elements but i need it into view model format.
thanks in advance
thanks phuzi its work for me :)
here I have changed some code block.
$("#btnSave").on("click", function () {
var ParamsList = [];
$('#paramsBlockTable tbody > tr').each(function () {
let SingleParams = {
Params_ID: $(this).find(".params-id").val(),
Params_CSS_Attribute: $(this).find(".params-attribute").val(),
Params_Priority: $(this).find(".params-priority").val()
}
ParamsList.push(SingleParams);
});
var ToolsModel = {
"ID": $("#ID").val(),
"Tools_Name": $("#Tools_Name").val(),
"Category_ID": $("#Category_ID").val(),
"Params_List": ParamsList,
"ScriptFiles_IDs": $("#ScriptFiles_IDs").val(),
"Tools_SEO_Keyword": $("#Tools_SEO_Keyword").val(),
"Tools_Desc": $("#Tools_Desc").val(),
}
console.log(ToolsModel);
});

Pass an Object from Angularjs to MVC controller and map to Class Object

I have an object in angularjs which I want to pass and map it to custom c# class in mvc controller. but whenever I am doing this class object is null completely.
$scope.Get = function () {
var EService = [{
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
}];
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
})
MVC Controller and Class:
[HttpPost]
public string Insert(ServicesMaster Service)
{
GIBCADBEntities gfientity = new GIBCADBEntities();
var record = "Sent"
return Json(record, JsonRequestBehavior.AllowGet);
} public class ServicesMaster
{
public string id { set; get; }
public string servicename { set; get; }
public string servicetype { set; get; }
public int? monthlyrental { set; get; }
public string serviceremarks { set; get; }
public byte servicestatus { set; get; }
public DateTime? activationdate { set; get; }
public DateTime? deactivationdate { set; get; }
}
The javascript variable/object "EService" is ok here, and when passing only the ServicesMaster object is created with null values and no data is mapped to it. I can send single string or any value from here but when sending a complete object its behaving like this.
You are passing an array from front end and fetching object from server end. just remove the "[" and "]" brace while set value to EService . Like :
$scope.Get = function () {
var Service = {};
Service = {
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
};
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
});
};
It should work now. :)

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

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.

Translate boolean to bool after Ajax call

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

Categories

Resources