i am working with the new VS2013 and created OData Controller with 2 models , Store and Products as client i have used KO,BreezeJS and DataJs
i saw that expand is not working, i have send this issue to microsoft poeple in codeplex site and they told me that all is ok with my code
my.vm = {
stores: ko.observableArray([]),
load: function () {
var serverAddress = "/odata";
breeze.config.initializeAdapterInstances({ dataService: "OData" });
var manager = new breeze.EntityManager(serverAddress);
var query = breeze.EntityQuery.from("Store").expand("Products");
manager.executeQuery(query, function (data) {
var results = data.results;
$.each(data.results, function (i, c) {
my.vm.stores.push(c);
});
});
}
};
adding the request/response
http://localhost:16894/odata/Store?$expand=Products
{
"odata.metadata":"/odata/$metadata#Store","value":[
{
"odata.type":"WebApplication1.Models.Store","odata.id":"/odata/Store(1)","Products#odata.navigationLinkUrl":"/odata/Store(1)/Products","Products":[
{
"odata.type":"WebApplication1.Models.Product","odata.id":/odata/Product(1)","ID":1,"Name":"1"
},{
"odata.type":"WebApplication1.Models.Product","odata.id":"/odata/Product(2)","ID":2,"Name":"2"
}
],"ID":1,"Name":"1"
},{
"odata.type":"WebApplication1.Models.Store","odata.id":/odata/Store(2)","Products#odata.navigationLinkUrl":"/odata/Store(2)/Products","Products":[
{
"odata.type":"WebApplication1.Models.Product","odata.id":"/odata/Product(2)","ID":2,"Name":"1"
},{
"odata.type":"WebApplication1.Models.Product","odata.id":"/odata/Product(3)","ID":3,"Name":"2"
}
],"ID":2,"Name":"1"
}
]
}
Related
I have asp.net mvc site with full calendar. I also created tables like 'Event' and 'Room'. In my event table i have RoomId field.
This is how my function looks:
$(document).ready(function () {
var events = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/CalendarEvent/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.Id,
title: v.Job,
description: v.Description,
start: moment(v.Start),
end: v.DutyEnd != null ? moment(v.End) : null,
room: v.RoomId,
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
}
On this moment, calendar displays Id. How can I refer to another table?
And this is my controller:
public JsonResult GetEvents()
{
using (Context dc = new Context())
{
dc.Configuration.LazyLoadingEnabled = false;
var events = dc.Event.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
You will need to join the event table with the room table. In your controller method GetEvents() you can create a select query something along the lines of the following:
var query = (from event in dc.event
join rooms in dc.rooms on event.roomId equals rooms.roomId
select new
{
eventID: event.Id,
title: event.Job,
description: event.Description,
roomId: room.RoomId,
roomName: room.Name
roomSize: room.Size
}).ToList();
Hope this helps.
I've tried different demo application of SAPUI5 like shoping cart, manage product. But I"m unable to solve my problem. I've two views. on home view I've set my model globally like
var model = this.getView().getModel('product');
var oModel = new sap.ui.model.json.JSONModel(model);
sap.ui.getCore().setModel(oModel, "product");
and then I'm navigating to product page. where i'm accessing my product name and trying to access my specific product to bind with my current view.
_routePatternMatched: function(oEvent) {
var name= oEvent.getParameter("arguments").name,
oView = this.getView(),
sPath = "/Product('" + sId + "')";
console.log(sPath);
var oModel = sap.ui.getCore().getModel("product");
var oData = oModel.getData(sPath);
console.log(oData);
oView.bindElement({
path: sPath,
events: {
dataRequested: function() {
oView.setBusy(true);
},
dataReceived: function() {
oView.setBusy(false);
}
}
});
//if there is no data the model has to request new data
if (!oData) {
oView.setBusyIndicatorDelay(0);
oView.getElementBinding().attachEventOnce("dataReceived", function() {
// reset to default
oView.setBusyIndicatorDelay(null);
this._checkIfCourseAvailable(sPath, name);
}.bind(this));
}
},
_checkIfCourseAvailable: function(sPath) {
var oModel = sap.ui.getCore().getModel("product");
var oData = oModel.getData(sPath);
// show not found page
if (!oData) {
this._router.getTargets().display("notFound");
}
},
I got the right result by filtering by id. now after giving path to var oData = oModel.getData(sPath);
console.log(oData); It have the right result but i'm unable to it do not show data on view i'm trying as {pruduct>/name}
pas model name in bindElement and then access via model name ..
oView.bindElement({
path: sPath,
model:modelName,
events: {
dataRequested: function() {
oView.setBusy(true);
},
dataReceived: function() {
oView.setBusy(false);
}
}
});
In view use {modelName>name}
I'm working with mvc4 and knockout trying to understand all the cool stuff you can to with it.
the thing is, i have this code which loads info and sends it to the view.
public ActionResult AdministraContenidoAlumno()
{
Alumno NuevoAlumno = new Alumno();
NuevoAlumno.AlumnoId = 1;
NuevoAlumno.NombreCompleto = "Luis Antonio Vega Herrera";
NuevoAlumno.PlanEstudioActual = new PlanEstudio
{
PlanEstudioId = 1,
NombrePlan = "Ingenieria en sistemas",
ListaMateriasPlan = new List<Materias> {
new Materias{MateriaId=1,NombreMateria="ingenieria 1"},new Materias{MateriaId=2,NombreMateria="Ingenieria 2"}
}
};
return View(NuevoAlumno);
Basically, create a new object alumno, who contains a PlanEstudio, who contains a list of Materias, then send it to the view.
In the view i have this.
#model MvcRCPG.Models.Alumno
#{
ViewBag.Title = "AdministraContenidoAlumno";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
var data;
$(function () {
var jsonModel = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
data = mvcModel;
ko.applyBindings(mvcModel);
});
function Guardar() {
$.ajax({
url: "/DemoKnockuot/GuardarAlumno",
type: "POST",
data: JSON.stringify({ 'NuevoAlumno': ko.toJS(data) }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data == "Success") {
alert('entro')
} else {
alert('trono')
}
},
error: function () {
alert("An error has occured!!!");
}
});
}
</script>
With the mentioned above functions i can read and send data to the server and do stuff on the controller, however i need to add remove or manipulate the information in the view.
So the question is: how do i add a function to 'mvcModel' in order to push a new "materia" in the ListaMateriasPlan object?
Thank you, and if you have more tips in order to understand it better i appreciate your help.
The mvcModel created by the mapping plugin will have observable properties.
For example, to add a new "materia" do something like:
function Materias() {
this.MateriaId = ko.observable();
this.NombreMateria = ko.observable();
}
var newItem = new Materias();
newItem.MateriaId(3);
newItem.NombreMateria("Ingenieria 3");
mvcModel.PlanEstudioActual.ListaMateriasPlan.push(newItem);
And normally, you would wrap the "adding" logic as a method in a view model.
I am using angularjs-rails-resource , in my Rails Angular App.
Account Resources
myApp.factory('Account', ['railsResourceFactory','railsSerializer', function
(railsResourceFactory,railsSerializer) {
return railsResourceFactory({
url: '/accounts',
name: 'account',
serializer: railsSerializer(function () {
this.nestedAttribute('address');
})
});
}]);
UserController.js
function userController($scope,$location,Auth,$rootScope,$http,Useraccount,Account) {
$scope.profileUpdate = function() {
//Useraccount.save(); // THIS WORKS
$scope.account = {}
$scope.account.save() // Throwing error : undefined function save
}
}
UserAccount Service
myApp.service('Useraccount',function(Auth,$location,$rootScope,Account){
var account;
var query = function(){
var promise = Account.query().then(function (results) {
account = results;
}, function (error) {
alert("Went Wrong while fetching User Account!!")
});
return promise;
}
var save = function() {
account.save().then(function (results) {
console.log(results);
}, function (error) {
alert("Went Wrong!!")
});
}
return {
query:query,
save:save
}
})
});
I am not sure why the save function from UserController is not working though I have imported Account resources as dependency. I did same in service , but it was working there. Any clue will be helpful.
You are actually calling the save() method for an empty javascript object. I don't see the point here.
Anyway you need an Angular object to do so. So either load account data from server.
$scope.accounts = Account.query(); // Will be an Array of accounts
Or create new instance of Account
$scope.account = new Account(); // An empty object
I am creating a view model in Knockout from a model in mvc4. I am using the mapping plugin. Current code looks like this.
First: I merge the different MVC4 models I need into a single ko viewmodel.
var mergedData = $.extend(true, {}, initialEventData,
{ "Tickets": initialTicketData }, { "TimeZones": timeZones }
);
Second: I add some mapping to add a computed function to my viewmodel.
var mapping = {
'Tickets': {
create: function (options) {
return new updatedTicket(options.data);
}
}
}
var updatedTicket = function (data) {
ko.mapping.fromJS(data, {}, this);
this.formattedPrice = ko.computed(function () {
return "$" + parseFloat(this.Price()).toFixed(2);
}, this);
}
Finlly: I apply the bindings.
var eventViewModel = ko.mapping.fromJS(mergedData, mapping);
However: Sometimes the Tickets model may come back empty. When this happens, the mapping plugin does not create the observable array (obviously). I need to have an empty array with mapped properties created so that I can push new tickets.
I would just add a check to the mapping configuration. Check if the data is there in the updatedTicket function and if it's not, manually create an observable array
just make a container viewmodel where you can create your default tickets array...
also in your callback functions, make sure you use a variable referring to "this"
var mapping = {
'Tickets': {
create: function (options) {
return new updatedTicket(options.data);
}
}
}
var updatedTicket = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
this.formattedPrice = ko.computed(function () {
return "$" + parseFloat(self.Price()).toFixed(2);
}, this);
}
var viewModel = function ( ) {
this.Tickets = ko.observableArray([]);
ko.mapping.fromJS(mergedData, mapping, this);
}
var eventViewModel = new viewModel();