MVC model binder issues when posting data from knockout - asp.net-mvc-4

I have a knockout model that I'm trying to post to an MVC4 controller. A simplified version looks like this:
var ItemModel = function (id, name) {
var self = this;
self.id = ko.observable(id);
self.name = ko.observable(name);
};
var Entry = function () {
var self = this;
self.Id = ko.observable();
self.areas = ko.observableArray([]);
};
var EntryModel = function () {
var self = this;
self.entry = new Entry();
self.save = function () {
$.post("/Edit", ko.toJS(self.entry), function (data) {
...
})};
};
};
If I add two areas to my model, like this:
viewModel.entry.areas.push(new ItemModel(1, "A"));
viewModel.entry.areas.push(new ItemModel(2, "B"));
and post it using viewModel.save I get two areas from the model binder, but no data in them (i.e. id = 0, name = "").
After some research I found that I'm posting data like this:
id = 1
name = test
area[0][id] = 1
area[0][name] = "A"
area[1][id] = 2
area[1][name] = "B"
and that MVC expects this:
id = 1
name = test
area[0].id = 1
area[0].name = "A"
area[1].id = 2
area[1].name = "B"
How do I get this posted as expected?

Your model contains the array so you have to stringify your model and send the resultant string to the controller. You can try this:
var EntryModel = function () {
var self = this;
self.entry = new Entry();
//toJSON function produce the JSON string representing entry model
var dataToSend = ko.toJSON(self.entry);
self.save = function () {
$.post("/Edit", dataToSend, function (data) {
...
})};
};
};

Related

How to pass HTML(View) Table data to controller to save in slq table

I am calculating the some values based on data available for previous month and displaying in table format in view. I have another model where I need to pass these values and save in database. I am not inputting any value, either values are static or calculated. Values are not passed from view to controller.
I have tried the jquery/ajax but not successful.
//Controller//
[HttpPost]
public JsonResult Proccess(List<ServerCount> deviceCounts)
{
if(deviceCounts == null)
{
deviceCounts = new List<ServerCount>();
}
var startOfTthisMonth = new DateTime(DateTime.Today.Year,
DateTime.Today.Month, 1);
var FromDate = startOfTthisMonth.AddMonths(-1);
var ToDate = startOfTthisMonth.AddDays(-1);
var billMonth = startOfTthisMonth.AddMonths(-1).ToString("MMM") + "-" + startOfTthisMonth.AddMonths(-1).ToString("yyyy");
ServerCount model = new ServerCount();
foreach (ServerCount sc in deviceCounts)
{
model.BillingMonth = billMonth;
model.ServiceName = sc.ServiceName;
model.BaslineVol = sc.BaslineVol;
model.ResourceUnit = sc.ResourceUnit;
model.DeviceCount = sc.DeviceCount;
model.DeployedServer = sc.DeployedServer;
model.RetiredServer = sc.RetiredServer;
_context.ServerCount.Add(model);
}
int insertRecords = _context.SaveChanges();
return Json(insertRecords);
}
==================
Jquery
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "#btnSave", function () {
var deviceCounts = new Array();
$("#tblServerCount TBODY TR").each(function () {
var row = $(this);
var deviceCount = {};
deviceCount.ServiceName = row.find("TD").eq(0).html();
deviceCount.BaslineVol = row.find("TD").eq(1).html();
deviceCount.ResourceUnit = row.find("TD").eq(2).html();
deviceCount.DeviceCount = row.find("TD").eq(3).html();
deviceCount.DeployedServer = row.find("TD").eq(4).html();
deviceCount.RetiredServer = row.find("TD").eq(5).html();
deviceCounts.push(deviceCount);
});
var model = $("#MyForm").serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Proccess", "DeviceCountServers", new { Area = "Admin" })?' +model,
data: JSON.stringify(deviceCounts),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
location.reload();
});
});
});
</script>
I looking that data from table is saved to sql on click of button

Table, computed property and vuex data

I'm in need of help with computed properties .. it's hard to explain but I'll try ..
I have a table with filter and pagination that I created.
When I pass the data directly from a request the API works,
but when I have to work with data coming from vuex I'm having trouble ...
Because I do not know when the data will be filled in vuex
And then I use the computed property because the moment the vuex is filled it will capture the data ..
However as the function that fills the data is the same one that is executed when I click on the page I crash the process and the page stops working.
Below is the computed property:
list(){
if (this.url_get == '' && this.$store.state.table.list.length > 0){
this.total_data = this.$store.state.table.list.length
this.repos = this.$store.state.table.list
this.getPaginatedItems(1)
}
var filter = this.configs.filter.toString().toLowerCase()
var items = ''
if (filter == ''){
items = this.dados
}else{
items = this.repos
}
const list = this.$lodash.orderBy(items, this.configs.orderBy, this.configs.order)
this.reverse = 1;
if (this.$lodash.isEmpty(filter)) {
return list;
}
var result = this.$lodash.filter(list, repo => {
return repo[this.filter_term].toString().toLowerCase().indexOf(filter) >= 0
})
return result
},
And the function:
getPaginatedItems(data) {
var items = this.repos
var page = data
var per_page = 10
var offset = (page - 1) * per_page
var max_item = offset+per_page
var paginatedItems = this.$lodash.slice(items, offset, max_item)
var obj = {
offset: offset,
current_page: page,
per_page: per_page,
total: items.length,
total_pages: Math.ceil(items.length / per_page),
data: paginatedItems,
last: offset+paginatedItems.length,
max_item: max_item
}
this.pagination = obj
this.dados = this.pagination.data
},
Request who fill the data in vuex
axios
.get(`api/getusuariosgrupo/${id}`)
.then(res => {
if (res.data.dados !== undefined && res.data.dados.length !== 0){
vmThis.isEditing = true
var d = {
list: res.data.dados,
length: res.data.dados.length
}
this.$store.commit('SET_TABLE', d)
}else{
vmThis.isEditing = false
}
vmThis.$bus.$emit('processando',{val: false})
})

Sensenet Content Picker Customization

I created two custom content types, ProjectContract and PaymentRequest. Under PaymentRequest, I have a reference field Contract which I would like to use to reference ProjectContract. When I am creating/changing PaymentRequest, I need the following:
how can I initialize Content Picker to display ContractNumber field of available ProjectContracts?
how can I display selected ProjectContract's ContractNumber under ReferenceField Grid control?
The SN js code and the mvc contains/returns fix field values. I did not find any setting where I can add custom fields to show.
First of all, what is the version of that SN package, because the oData.svc request will not work on older versions. It is available from 6.2.
About the oData, here is a link: http://wiki.sensenet.com/OData_REST_API
There is another way to solve it, but with this, you need to modify the existion SN codes.
You need to copy (" /Root/Global/scripts/sn/SN.Picker.js ") file into your skin folder with the same structure. (" /Root/Skins/[yourskinfolder]/scripts/sn/SN.ReferenceGrid.js ")
You need to copy (" /Root/Global/scripts/sn/SN.ReferenceGrid.js ") file into your skin folder as well.
Do not modify the original SN file, because it will be overwrite after an SN update.
Next step: copy the following code to line 1068, before the ("$grid.jqGrid({") line, into the InitGrid function.
...
var neededTypeName = "ProjectContract";
var neededFieldName = "ContractNumber";
var findField = false;
o2 = (function () {
var result = [];
var itemArray = [];
$.each(o2, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
colNames.splice(6, 0, "ContentField");
colModel.splice(6, 0, { index: "ContentField", name: "ContentField", width: 100 });
return result;
}
return o2;
})();
...
$grid.jqGrid({
...
The "neededTypeName" may contains your content type value, and the "neededFieldName" may contains the field name you want to render.
The other will build up the grid.
This will modify the Content picker table.
You need to add this code into the GetResultDataFromRow function, at line 660 before the return of the function.
...
if (rowdata.ContentField != undefined) {
result.ContentField = rowdata.ContentField;
}
...
This will add the selected item properties from the Content picker to the reference field table.
Then you need to open the SN.ReferenceGrid.js and add the following code into the init function before the "var $grid = $("#" + displayAreaId);"
var neededTypeName = "CustomItem2";
var neededFieldName = "Custom2Num";
var findField = false;
var alreadyAdded = false;
var btnAttr = $("#"+addButtonId).attr("onClick");
if (btnAttr.indexOf(neededTypeName) > -1) {
alreadyAdded = true;
colNames[4].width = 150;
colModel[4].width = 150;
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 60 });
}
initialSelection = (function () {
var result = [];
var itemArray = [];
$.each(initialSelection, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
if (!alreadyAdded) {
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 100 });
}
return result;
}
return initialSelection;
})();
I hope this will help but the SN version should be helpful.

knockout mapping to be done only first time

I am generating the knockout mapping from server side view model using below
var bindData2ViewModel = function (data) {
var rdata = ko.toJSON(data);
ko.mapping.fromJSON(rdata, {}, vm.model());
ko.applyBindings(vm);
};
var CustomerViewModel = function () {
var self = this;
self.model = ko.observable({});
return { model: self.model };
};
var vm = new CustomerViewModel();
now there is another call which is giving me the data... i just want to bind that data to the client side viewmodel without changing the binding... how to do that?
var rebindData2ViewModel = function (data) {
var rdata = ko.toJSON(data);
vm.model.set(rdata);
ko.applyBindings(vm);
};
tried above but not working... what is the correct way to do this?
basically to rebind the data to the existing model.. you just need to set the data using the angular brackets.. no need of json etc... because data should itself return as jsonresult
var rebindData2ViewModel = function (data) {
vm.model(data);
};

google maps api v2 map.removeOverlay() marker array issue

To start off with, I would like to say that I have been looking on the internet for a really long time and have been unable to find the answer, hence my question here.
My latest school project is to create an admin page for adding articles to a database, the articles are connected to a point on a google map. The requirement for adding the point on the map is that the user is able to click the map once and the marker is produced, if the map is clicked a second time the first marker is moved to the second location. (this is what I am struggling with.)
The problem is, as the code is now, I get the error that markersArray is undefined. If I place the var markersArray = new Array; underneath the eventListener then I get an error that there is something wrong the main.js (googles file) and markersArray[0] is undefined in the second if.
By the way, I have to use google maps API v2, even though it is old.
<script type="text/javascript">
//<![CDATA[
var map;
var markers = new Array;
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
if (this.counter == 0) {
if (latlng) {
var marker = new GMarker(latlng);
latlng1 = latlng;
this.map.addOverlay(marker);
this.counter++;
markers.push(marker); //This is where I get the error that markersArray is undefined.
}
}
else if (this.counter == 1) {
if (latlng){
alert (markers[0]);
this.map.removeOverlay(markers[0]);
var markers = [];
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}
I solved the problem. I'm not exactly sure why it worked but this is what it looks like now:
var markersArray = [];
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var type = Articles[i].getAttribute("type");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
var marker = new GMarker(latlng);
if (this.counter == 0) {
if (latlng) {
latlng1 = latlng;
this.map.addOverlay(marker);
markersArray.push(marker);
this.counter++;
}
}
else if (this.counter == 1) {
if (latlng){
this.map.removeOverlay(markersArray[0]);
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}