How to retrieve a web-api controller method(without database), from Javascript - javascript

I want to retrieve the function/method written in controller of Web-Api, from javascript of multi-channel devextreme template.(need to show data from Web-API Controller in front-end, where data is not from server).
Please suggest me which site I should refer/by writing simple code...
Controller
namespace WebApiODataService3.Controllers
{
public class ShaileshsController : ODataController
{
public string GetShailesh()
{
return "say hello";
}
}
}
shailesh.js of shailesh.dxview-from devextreme multichannel template
Application2.shailesh = function (params) {
"use strict";
var viewModel = {
// Put the binding properties here
};
return viewModel;
};

I think you ask for an example:
Classes
public class CustomModel
{
public int var1 { get; set; }
public string var2 { get; set; }
public IEnumerable<SubSetModel> subset { get; set; }
}
public class SubSetModel
{
public string subvar1 { get; set; }
public string subvar2 { get; set; }
}
Test Controller Methods
[Route("api/route/postaction")]
public System.Web.Http.Results.JsonResult<string> postaction(CustomModel data)
{
return Json<string>("ok");
}
[Route("api/route/getaction")]
public dynamic getaction()
{
var data = new CustomModel() { var1 = 1, var2 = "ter" };
data.subset = new List<SubSetModel>() { new SubSetModel() { subvar1 = "hi", subvar2 = "hola" } };
return data;
}
Call to getaction
$.ajax({
url: "http://localhost:45007/api/maestro/getaction",
method: "GET",
data: {}
}).done(function (dataSel) {
alert("OK");
}).fail(function (dataSel) {
alert("Fail");
});

Related

Pass multiple json objects throught ajax to razor pages

I am trying to pass multiple parameters using ajax 'data:'. In cs file parameter model is null.
What am I doing wrong here? I've tried with and without JSON.stringify
this is in chtml razor page.
var Obj_A = [];
var obj = {};
var inputs = $("#fieldset1 input[name^=show_all_]");
for(var i = 0; i < inputs.length; i++){
var text_id = $(inputs[i]).attr("id").replace('show_all_','');
var value = $(inputs[i]).val();
obj[text_id]=value;
}
Obj_A.push(obj);
.
.
same for Obj_B
.
var model = {
Item_1: Obj_A ,
Item_2: Obj_B
};
$("#btn_insert").click(function () {
$.ajax({
type: "POST",
url: "/Home/Edit?handler=Import",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(model),
contentType: "application/json",
success: function (response) {
},
error: function (e) {
}
});
});
console.log for model has values.
this is in chtml.cs razor page.
public async Task<JsonResult> OnPostImport([FromBody]All_Obj model)
{
{
return new JsonResult(new { message = "2", filename = "1" });
}
}
model parameter is always null.
model class
public class model
{
public Item_1 field_1 { get; set; }
public Item_2 field_2 { get; set; }
}
Item_1 class
public class Item_1
{
public string field_item_1_1 { get; set; }
public string field_item_1_2 { get; set; }
public string field_item_1_3 { get; set; }
}
Item_2 class
public class Item_2
{
public string field_item_2_1 { get; set; }
public string field_item_2_2 { get; set; }
public string field_item_2_3 { get; set; }
}
Please use the following code to add data to model:
var Obj_A = {};
Obj_A.field_item_1_1=$("#show_all_field_item_1_1").val();
Obj_A.field_item_1_2=$("#show_all_field_item_1_2").val();
Obj_A.field_item_1_3=$("#show_all_field_item_1_3").val();
var Obj_B = {};
Obj_B.field_item_2_1=$("#show_all_field_item_2_1").val();
Obj_B.field_item_2_2=$("#show_all_field_item_2_2").val();
Obj_B.field_item_2_3=$("#show_all_field_item_2_3").val();
So that the model structure will be like this:

Passing Form Serialize and list to controller is not working?

i have controller like this:
public ActionResult SaveWorkOrder(DTO_WorkOrder objWork, List<DTO_PartsWO> listTry)
{
//something
}
and model :
public class DTO_WorkOrder
{
public string Id { get; set; }
public string WoNo { get; set; }
public string ReqNo { get; set; }
public string ReqSparepartDate { get; set; }
public List<DTO_PartsWO> PartsList { get; set; }
}
this is my javascript to pass data to controller:
function SaveWorkOrder()
{
debugger;
var dd = $('#tbParts').DataTable().rows().data().toArray();
var vDataDet = new Array();
//Loop through the Table rows and build a JSON array.
$.each(dd, function (i, value) {
debugger;
var dataDetail = {};
dataDetail.Line = i;
dataDetail.PartCode = value[1];
dataDetail.PartDesc = value[2];
vDataDet.push(dataDetail);
debugger;
});
var tmp = $('#WorkOrderForm').serialize();
$.ajax({
type: 'POST',
url: '/Transactions/WorkOrder/SaveWorkOrder',
data: JSON.stringify({ objWork: tmp, listTry: vDataDet}),
success: function (mdl)
{
debugger;
},
error: function (mdl)
{
debugger;
}
)}
}
the codes pass the serialize form but not the list, my list null...
please help, already code for 3 days to pass both list and serialize form but not worked
I don't know if this is the right way, but it is working fine, instead using serialize, serializeArray work good so I can add list parameter in form, so this is the code I use:
function SaveWorkOrder()
{
debugger;
var dd = $('#tbParts').DataTable().rows().data().toArray();
var vDataDet = new Array();
// step 1 serialize array the form
var data = $("#WorkOrderForm").serializeArray();
//Loop through the Table rows and build a JSON array.
$.each(dd, function (i, value) {
debugger;
data[data.length] = { name: "PartsList[" + i + "].Line", value: i };
data[data.length] = { name: "PartsList[" + i + "].PartCode", value: value[1] };
data[data.length] = { name: "PartsList[" + i + "].PartName", value: value[2] };
debugger;
});
$.ajax({
type: 'POST',
url: '/Transactions/WorkOrder/SaveWorkOrder',
data: data,
success: function (mdl)
{
debugger;
},
error: function (mdl)
{
debugger;
}
})
}
This is the controller:
public ActionResult SaveWorkOrder(DTO_WorkOrder objWork)
{
//something
}
This is the models:
public class DTO_WorkOrder
{
public string Id { get; set; }
public string WoNo { get; set; }
public string ReqNo { get; set; }
public string ReqSparepartDate { get; set; }
public List<DTO_PartsWO> PartsList { get; set; }
}
public class DTO_PartsWO
{
public string WoNo { get; set; }
public Int32 Line { get; set; }
public string PartCode { get; set; }
public string PartName { get; set; }
}
you can see the result in pictureList in Object and detail List.

ASP.Net Core 3 Posting JSON array to controller

I´m having issues passing an array of JSON objects to an MVC controller in ASP.Net core 3. The JSON object is built from a CSV file and passed through an AJAX call. The correct action is called but the object received is always null.
JS:
async function updateData(){
var obj = await getData();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/admin/metric/Update",
data: obj,
dataType: 'json',
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
async function getData(){
var metric = {};
var metrics = [];
var response = await fetch('https://bloburi.net/source/file.csv');
var data = await response.text();
var table = data.split('\n').slice(1);
table.forEach(row => {
var columns = row.split(',');
metric["FirstName"] = columns[0];
metric["LastName"] = columns[1];
metric["Email"] = columns[2];
metric["AverageHandleTime"] = columns[3];
metric["AverageFollowUp"] = columns[4];
metric["AverageHold"] = columns[5];
metric["Date"] = columns[6];
metrics.push(JSON.stringify(metric));
});
console.log(metrics);
return metrics;
}
Models:
public class MetricBase
{
[Required]
public string Date { get; set; }
public double AverageHandleTime { get; set; }
public double AverageHold { get; set; }
public double AverageFollowUp { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MetricModel
{
public IEnumerable<MetricBase> MetricBase { get; set; }
}
Controller:
[HttpPost]
public IActionResult Update([FromBody]MetricModel obj)
{
return Json(new { obj });
}
I think the issue may be on how I'm deffining the class that is receiving the JSON, but I've tried multiple things like deffining MetricBase as a List<> or straight up as an array in MetricModel, but it doesn't seem to work.
Any help is appreciated!
You adding the stringify item inside array via code
metrics.push(JSON.stringify(metric));
instead of stringify the whole array. Change the line to
metrics.push(metric);
and data: obj, to
data: JSON.stringify(obj),.
With the mentioned change, the $.ajax sends the whole array. Also change the action to
public IActionResult Update([FromBody]IEnumerable<MetricBase> obj)

AngularJS ngResource POST object is Null in C# Web API

My problem is that when I send a complete Javascript object to my Web API Controller I always get null values. Even though I have a complete object I need to specify each attribute and value as you can see below. How can I make Web API accept a ready made Javascript object and bind it correctly?
C# Web Api Controller:
[Route("addcredentials/{salesId}")]
[HttpPost]
public IHttpActionResult AddCredentials([FromUri] int salesId, [FromBody] ScriveCredentials credentials)
{
return Ok(credentials);
}
C# Credentials object:
public class Credentials
{
public string ClientIdentifier { get; set; }
public string ClientSecret { get; set; }
public string TokenIdentifier { get; set; }
public string TokenSecret { get; set; }
}
Javascript object passed to resource, saved as "result" further down:
{ClientIdentifier: "a", ClientSecret: "b", TokenIdentifier: "c", TokenSecret: "d"}
Resource method:
addCredentials: {
method: 'POST',
url: 'api/addcredentials/:userSalesId'
}
Usage that results in null values:
userResource.addCredentials({ userSalesId: user.SalesId }, { credentials: result}).$promise.then(function (data) {
console.log(data);
});
Payload for this request:
{"credentials":{"ClientIdentifier":"a","ClientSecret":"b","TokenIdentifier":"c","TokenSecret":"d"}}
Usage that works but seems overly complicated:
userResource.addCredentials({ userSalesId: user.SalesId }, { ClientIdentifier: result.ClientIdentifier, ClientSecret: result.ClientSecret, TokenIdentifier: result.TokenIdentifier, TokenSecret: result.TokenSecret }).$promise.then(function (data) {
console.log(data);
});
Request payload:
{"ClientIdentifier":"a","ClientSecret":"b","TokenIdentifier":"c","TokenSecret":"d"}
Update
Tried the following and it did not work either, null on all values:
addScriveCredentials: {
method: 'POST',
url: 'api/addcredentials/'
result.SalesId = user.SalesId;
userResource.addCredentials({}, { credentials: result }).$promise.then(function (data) {
console.log(data);
});
C#:
[Route("addcredentials")]
[HttpPost]
public IHttpActionResult Addcredentials(Credentials credentials)
{
return Ok(credentials);
}
I had done a sample earlier, hope the follwing code will help you to understand.
The Model.
using System.ComponentModel.DataAnnotations;
public class ProductModel
{
public ProductModel(int id, string name, string category, decimal price)
{
Id = id;
Name = name;
Category = category;
Price = price;
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Category { get; set; }
[Required]
public decimal Price { get; set; }
}
The ApiController.
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using System.Web.Http;
public class ProductsController : ApiController
{
// other code omitted for brevity.
[HttpPost]
public IHttpActionResult PostProduct(ProductModel product)
{
try
{
if (product == null)
{
throw new ArgumentNullException("Product parameter cannot be null");
}
if (ModelState.IsValid)
{
// code omitted for brevity.
return this.Ok();
}
else
{
throw new Exception("Product is invalid");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPut]
public IHttpActionResult PutProduct(ProductModel product)
{
try
{
if (product == null)
{
throw new ArgumentNullException("Product parameter cannot be null");
}
if (ModelState.IsValid && product.Id > 0)
{
// code omitted for brevity.
return this.Ok();
}
else
{
throw new Exception("Product is invalid");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
// other code omitted for brevity.
}
The Angular service.
// products.js
(function () {
"use strict";
angular
.module("exampleApp")
.constant("baseUrl", "http://localhost:53631/api/products/")
.factory("productsResource", productsResource);
productsResource.$inject = ["$resource", "baseUrl"];
function productsResource($resource, baseUrl) {
return $resource(baseUrl + ":id",
{
id: "#id"
},
{
create: {
method: "POST"
},
save: {
method: "PUT"
}
});
}
})();
The Angular controller. Focus on createProduct and updateProduct functions below
// edit.controller.js
(function () {
"use strict";
angular
.module("exampleApp")
.controller("EditController", EditController);
EditController.$inject = ["$routeParams", "$location", "productsResource"];
function EditController($routeParams, $location, productsResource) {
var vm = this;
vm.currentProduct = null;
vm.createProduct = createProduct;
vm.updateProduct = updateProduct;
vm.saveEdit = saveEdit;
vm.cancelEdit = cancelEdit;
if ($location.path().indexOf("/edit/") === 0) {
var id = $routeParams.id;
productsResource.get({ id: id }, function (data) {
vm.currentProduct = data;
});
}
function cancelEdit() {
$location.path("/list");
}
function updateProduct(product) {
product.$save().then(function () {
$location.path("/list");
});
}
function saveEdit(product) {
if (angular.isDefined(product.id)) {
vm.updateProduct(product);
} else {
vm.createProduct(product);
}
vm.currentProduct = {};
}
function createProduct(product) {
new productsResource(product).$create().then(function (newProduct) {
$location.path("/list");
});
}
}
})();
You could pass one object as the body of the post message instead.
Add a class like this
public class addCredentialObj
{
public int salesId { get; set; }
public Credentials credentials { get; set; }
}
Modify your controller like this (The use of FromBody can be read here)
[Route("addcredentials")]
[HttpPost]
public IHttpActionResult AddCredentials([FromBody]addCredentialObj obj)
{
return Ok(credentials);
}
In the client you need to create a matching json object to the addCredentialObj class
var yourCredentials = {"ClientIdentifier":"a","ClientSecret":"b","TokenIdentifier":"c","TokenSecret":"d"};
var jsonData = {
salesId: yourId,
credentials: yourCredentials
};
And then in the $http request to the controller, stringify the json object
$http({
method: 'POST',
url: 'api/addcredentials',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
data: JSON.stringify(jsonData),
});

add data on sql using javascript

Hello i want to add data on database in sql but i can't find how to do this using javascript,i work on visual studio
You can use Javascript to pass data back to your .NET MVC C# Controller method
var myViewModel = {};
var team= {};
team.TeamID = 1234;
team.TeamName = "Test Team";
myViewModel.Team= team;
var teamPlayerList = [];
var player1= {};
player1.id= "1";
player1.Name = "Patrick";
var player2 = {};
player2.id= "2";
player2.Name = "Padraig";
teamPlayerList.push(player1);
teamPlayerList.push(player2 );
myViewModel.TeamPlayerList = teamPlayerList;
$.ajax(
{
url: 'Team/Create',
data: JSON.stringify({teamViewModel : myViewModel}),
contentType: 'application/json',
dataType: 'json',
type: 'POST',
success: function (data) {
alert("success");
},
error: function () { alert('error'); }
});
On the backend in the C# you will need A controller class, and some C# classes to hold the data you pass in from javascript
public class Team
{
public long TeamID { get; set; }
public string TeamName { get; set; }
}
public class TeamPlayer
{
public string id{ get; set; }
public string Name { get; set; }
}
A ViewModel
public class TeamViewModel
{
public Team Team { get; set; }
public IList<TeamPlayer> TeamPlayerList { get; set; }
}
The controllers method will be something like this
public class TeamController : Controller
{
[HttpPost]
public ActionResult Create(TeamViewModel teamViewModel)
{
//USE HERE TO EXTRACT DATA PASSED IN
var myTeam = teamViewModel.Team;
var teamPlayerList = teamViewModel.TeamPlayerList;
//call your db insert class/code and use values passed in
return Content("success");
}

Categories