ASP.Net MVC with Angular and Kendo UI - angularjs

I'm new to ASP, Kendo and programming in general.
I’m trying to use Kendo Grid to CRUD the database; but I am kind of lost.
I have a simple class: Person, with Name and Surname.
The generated Controller and View works just fine, I can CRUD the database.
Then, using Angular I created this module:
`angular.module("KendoDemos2", ["kendo.directives"])
.controller("MyCtrl2", function ($scope) {
$scope.mainGridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: { url: "/Person/Read", dataType: "json" },
create: { url: "/Person/Create", dataType: "json", type: "POST" },
update: { url: "/Person/Update", dataType: "json", type: "PUT" },
destroy: { url: "/Person/Delete", dataType: "json", type: "DELETE" },
parameterMap: function (options, operation) {
if (operation !== "read") {
console.log(options)
return kendo.stringify(options);
}
}
},
batch: false,
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Name: { type: "string },
Surname: { type: "string" } }
}
}
})`
The problem is:
First, When I create a new person on the Grid, when I press “Create”, I don’t know if the data is being passed to the controller.
Second, in the controller, I have no idea of how to receive this information (a json, I believe).
Sorry, I am a total beginner.
EDIT
I have this method on the Controller:
[HttpPost]
public ActionResult Create(Person model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has Occurred");
}
}
So, this is being sent to the Person/Create method:
{ Name: "John", Surname: "Doe"}
Which return Success;
But how do I get these properties from the Json, and populate the model?

Ok so.
POST = create
GET = well Get in the context of the type of request from
browser to server
PUT = Update
DELETE = exactly Delete
so those are the verbs associated with HTTP in which RESTFUL APIS reside, for the most part there are lot more to look at, behind the scope of this answer.
as a result of the nature of the call it already understands that certain things like the type of data that you sent was in Content-Type: application/json.
The one thing missing from that method which I am surprised it wasn't there was
[FromBody], unless you hand coded the Method yourself rather than scaffolded it. Understandable for someone starting out. :)
to see this placing one of those break points next to the if statement will allow you to see if model was indeed populated with the contents of the post call.
[HttpPost] //because we want to create (new Person(){}) right?
public ActionResult Create([FromBody] Person model){
if(model != null && model.IsValid){
//EntityFramework or what ever DB you are using
_context.Person.Add(model);
_context.SaveChanges();
//doing this returns to the client that it was created as well as the
//Id of the newly inserted record. model.Id was automagically updated with the Id.
return Created("api/person/create", model);
}
else{
//something was horribly wrong with the model sent
return BadRequest("Invalid Model");
}
}
I think that will cover the broad strokes of the question. I think you are using an older version of asp.net so JsonResult might be available as well, BadRequest and Created assume ApiController is being used or Controller in Asp.net Core

mvermef, thank you very much for all the explanation.
I’m using ASP.Net MVC 5, with EF.
I did as you told and it work perfectly.
I haven’t included Web API at first, but needed it to make the [FromBody] work.
Another small but important thing was include contentType on the kendo configuration:
create: { url: "/Person/Create", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8" },

Related

How to send form data from Angularjs to Django

I did the application on the sample from this lesson. Here, using DRF, a list of all added games is displayed on the page. I would really like to learn how to write a simple form of adding a new record to the database (two fields: title and description [as in the example]).
With js, I'm not very familiar with so far, so I do not know which side to get close to solving the problem.
$scope.saveUser = function(event) {
postForm({ id: 0 }, $('#FormName'), $scope, function(data) {
})
}
function postForm(postInfo, form, $scope, callback,) {
var postData = new FormData(form.get(0));
$.each(postInfo, function(key, value) {
postData.append(key, value);
});
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: postData,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
headers: {
"X-CSRFToken": app.getStorage("csrftoken")
},
beforeSend: function() {
$('#loading-image').show();
},
complete: function() {
$('#loading-image').hide();
if(typeof saveButtonId !== typeof undefined) {
$('#'+saveButtonId).removeAttr('disabled');
}
},
success: function(data) {
},
error: function(data) {
//
}
});
};
you'd be updating code in your mysite/backend folder to have some incoming route to insert data into django db using some serializer
sorry I don't have more specific details, but just wanted to convey the general idea
Here's some more information on Django serializers: http://www.django-rest-framework.org/api-guide/serializers/
another tutorial on adding an additional route to django could help

Kendo Grid Pass Form Data as Parameter Angular to MVC

I am switching from the Angular UI-Grid to the Kendo UI-Grid in my application. Currently, search criteria is collected via a search form then sent to my MVC Controller method via a Service (like below):
generalsearchService.submitSearch($scope.form)
.success(function (data) {
$scope.gridOptions.data = (data);
});
However, I cannot figure out how to pass the form data to the method using the Kendo grid. I have tried the following:
var form = $scope.form;
$scope.mainGridOptions = {
dataSource: new kendo.data.DataSource({
type: "aspnetmvc-ajax",
transport: {
read: "/SSQV4/SSQV5/Search/SubmitCriteria",
type: "POST",
data:{form: form}
},
schema: {
data: "Data",
total: "Total"
},
pageSize: 25,
serverPaging: true,
serverFiltering: true,
serverSorting: true
}),
My MVC Controller method (first line):
public async Task<ActionResult> SubmitCriteria(ContractorSearchViewModel form)
Update: I was able to pass the parameter to the controller by changing the read url to a function like below:
read: function() {
generalsearchService.submitSearch(form)
.success(function (data) {
return data;
});
}
However, even though the method executes correctly, the grid does not update with the new data.
Any assistance is greatly appreciated!
Although the service call above was hitting the MVC controller, the data was not populating the grid. The service call needed to be tweaked a little. Here is what finally worked:
dataSource: new kendo.data.DataSource({
transport: {
read: function (e) {
generalsearchService.submitSearch(e.data, form)
.then(function success(response) {
e.success(response.data);
});
}
},
schema: {
data: "Data",
total: "Total"
},
pageSize: 25,
serverPaging: true,
serverFiltering: true,
serverSorting: true
}),
"e.data" actually sends the Page, PageSize, Filters and Sort information while "form" is the collected form data which serves as parameters for the stored procedure. I also had to remove "[DataSourceRequest]" for the DataSourceRequest to actually send all information using my service. The http call in the service looks like this:
this.submitSearch = function (command, form) {
return $http.post('/SSQV4/SSQV5/Search/SubmitCriteria', {'command': command, 'form': form});
};
and the MVC controller method looks like this:
public async Task<ActionResult> SubmitCriteria(DataSourceRequest command, ContractorSearchViewModel form)
I hope this helps someone else. Happy coding!

Kendo grid read datasource with http post response

I am new at Kendo UI, I was using datatables to show values,here is my old code (Working):
$http.post("/reports/api/g3swmf/report", $scope.g3sWmf ).success(function(data){
$scope.reportVal += " - " + data;
}).then(function (response){
$scope.items=response.data;
}
And here is Kendo UI version (not Working):
$scope.g3sGridOptions = {
toolbar: ["excel"],
excel: {
allPages: true
},
dataSource: {
type: "json",
transport: {
read: {
url:("/reports/api/g3swmf/report", $scope.g3sWmf ),
type: "post",
dataType: "json"
}
},
schema: {
model: {
fields: {
poloCode: { type: "string" },
}
}
}
}
The kendo's transport url is suppose to be a string.
url:"/reports/api/g3swmf/report"
It doesn't handle the same the $http.post does. In fact, it pass the read parameter directly to jquery.ajax.
There's 2 way to solve this.
Use a string url for your transport
Define your transport.read as a function. You'll then be able to call you're own $http.post. If you define a function, note that kendo will provide a event parameter with some callback methods that should be used to send the data back to the grid.
Here's a custom read example:
read: function (readOptions) {
$http.post("/reports/api/g3swmf/report", $scope.g3sWmf ).success(function(data){
readOptions.success(data);
})
}
Please refer to kendo dataSource API documentation for more details

Web2py and Sencha

I'm new to Web2py and Sencha, and I would like to see a simple example using both frameworks. I have googled but I haven't found anything.
Many thanks for your help.
Finally I got everything working. To ensure that the js files are rendered it is necessary to paste them in the static folder of the web2py project. With Sencha Architect I have created a project in the mentioned location, so for example to call the controller from the js view an Ext.Ajax.request is made:
onDataRender: function(component, eOpts) {
Ext.Ajax.request
({
url: '/r/rec/getdata',
method: 'GET',
params: '',
success: function(response)
{
o=Ext.decode(response.responseText);
component.setSource(o);
console.log(response.responseText);
},
failure: function(response)
{
component.setSource({"Error" : "No data"});
console.log(response.responseText);
}
});
},
The controller then gets the resquested data from database, generates a json and returns it to the view layer:
def getdata():
jsondata="{"
data=db.song.find()
for s in data:
jsondata+="\""+str(s["_id"])+"\" : \""+str(s["name"]).replace("\"","")+"\","
return jsondata[:-1]+"}"
The getdata method gets all the data (it is a test example), to get a specific record the id can be passed as a parameter with request.args(0).

Model without a Store

I created a model which contains a proxy to load a single record and its takes no params. I don't want to use a store since I'll never have more then one record. I create an instance of the Model but can't figure out how to tell it to call and load the record from the server. This is the only example I could find, but I don't have an id to pass.
User.load(123, {
success: function(user) {
console.log("Loaded user 123: " + user.get('name'));
}
});
Also I'm making and ajax call and not a rest call in case that matters.
The load(id, [config]) is static and will return provide you with a new record instance. It uses the proxy that was set via setProxy(proxy) (also static). Per default it will send a read request with the params id: 123. The static method allows you to set some default callbacks within the optional config object. These callbacks are needed to get the instance of the loaded record (or the error).
How it works
// create a Model class
Ext.define('MyApp.User', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'}
]
});
// apply a proxy instance
MyApp.User.setProxy(/*YourAjaxProxy*/);
// prepare a handler
var cb = function(model, op) {
// log the new model instance
console.log(model);
};
// get a instance
MyApp.User.load(123, {
scope: this, // should be the scope of the callback (cb)
success: cb
});
Not what you need? Just comment...
Just make an Ajax request and store the result in a variable.
Ext.Ajax.request({
url: '/data/get',
method: 'GET',
params: {
requestID: 'XXXX',
connName: 'yyyy'
},
success: function (responseData) {
var countResult = Ext.decode(responseData.responseText); }
});

Resources