How to display Array from console log to asp.net mvc - asp.net

Hello guys i been searching for 2 days now on how to display the data from object that are seen in the picture.
here is my code in Ajax
$.ajax({
url: url,
data: { systemID: selectid },
success: function (jsonData) {
console.log(jsonData);
if (jsonData != null) {
console.log("enterif");
$('#sapNumber').val(jsonData.SapNumber);
$('#careerLevel').val(jsonData.SapLevel);
$('#seatsReleased').val(jsonData.SeatsReleased);
$('#noOfSR').val(jsonData.NumberOfSR);
$('#revenueLost').val(jsonData.RevenueLost);
$('#releaseDate').val(jsonData.ReleaseDate);
$('#fte').val(jsonData.FTE);
console.log("enterif2");
$('#releaseType').val(jsonData.ReleaseType);
$('#category').val(jsonData.Category);
$('#ctsID').val(jsonData.CTSID);
$('#agileHours').val(jsonData.AgileHours);
$('#fTERedeployment').val(jsonData.FTERedeployment);
$('#contractName').val(jsonData.ContractName);
$('#masterContractName').val(jsonData.MasterContractNumber);
$('#fromWBS').val(jsonData.FromWBS);
$('#toWBS').val(jsonData.ToWBS);
$('#comment').val(jsonData.Comment);
}
}

Related

What is the issue with asp.net route

This is from asp.net 5 / mvc 6. I have two controller methods, each takes a single parameter and each returns a string. One method takes a string parameter and the other takes a simple object. The method that takes the string parameter does not work (the value for the incoming parameter is always null). The call that passes in the simple object does work. I am making the calls to these methods from inside an angular controller using the $http service. I must be doing something wrong that is very simple, but I don't see it.
Here is the code for the controller class:
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpPost("PostWithStringParam")]
public string PostWithStringParam([FromBody] string val)
{
return val ?? "<null>";
}
[HttpPost("PostWithInputparam")]
public string PostWithInputParam([FromBody] TestInputClass val)
{
string ret = "<null>";
if (val != null)
{
ret = $"First Name: {val.Name}, City: {val.City}";
}
return ret;
}
}
Here is the relevant code from the angular controller. Note the the "go" function is wired up to ng-click from a button.
vm.inputObject = {
name: "George",
city: "Chicago"
}
vm.inputString = "some data";
var callApi = function(url, data) {
$http({
method: "POST",
url: url,
data: data
}).then(
function (result) {
alert(result.data);
},
function (error) {
alert(error.status);
}
);
}
var callStringApi = function() {
var url = "api/values/PostWithStringParam";
callApi(url, vm.inputString);
}
var callObjectApi = function () {
var url = "api/values/PostWithInputParam";
callApi(url, vm.inputObject);
}
vm.go = function() {
callStringApi();
callObjectApi();
}
Can someone please tell me why the method that takes the input string doesn't work??
Thanks!
You need to strinfigy the data and specify the contentType as application/json when sending data. The default model binder will be able to map the posted data then.
var callApi = function(url, data) {
$http({
method: "POST",
url: url,
data: JSON.stringify(data),
contentType:"application/json"
}).then(
function (result) {
alert(result.data);
},
function (error) {
alert(error.status);
}
);
}

calling one of multiple services in angularJS $resource

Is there anything wrong with this code where I am trying to have one service method point to different restful services?
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function ($resource) {
return {
pList: $resource('/:url/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { url: 'MyAngularScripts', phoneId: 'jsonPhonedata' }, isArray: true }
}),
pDetail: $resource('/Content/PhonesData/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { phoneId: $routeParams.phoneId }, isArray: false }
})
};
}]);
Then in my controller I call the pList like this:
$scope.phones = Phone.pList.query();
The service method doesnt get called with any of the code above. However if I change the service to this:
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function ($resource) {
return $resource('/:url/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { url: 'MyAngularScripts', phoneId: 'jsonPhonedata' }, isArray: true }
});
}]);
and call from the controller like this:
$scope.phones = Phone.query();
IT works. What is wrong with the service where I have multiple restful calls declared? SOmething wrong with the way its configured or the way I am calling it?
The 1st approach should be working fine as well.
The only oroblem is that you are trying to access a property of $routeParams, without first injecting it via DI, thus resulting in an Error being thrown.
If you correct this, everything should work as expected.

Google chart using JSON - Format issue - ASP.net - "Table has no columns”

I am seeing 2 types of JSON format out there and getting really confused.
I a trying to do the following:
I have an excel model with a range
Type RV
MRC 10
CRC 20
CVA 30
OpRisk 0
Using ExCelToWeb vba function from cDataSet (http://ramblings.mcpher.com/Home/excelquirks/json/excel-json-conversion), I convert this range to a JSON string. Output is as follows:
{ "cDataSet":[
{
"Type":"MRC",
"RV":10
},
{
"Type":"CRC",
"RV":20
},
{
"Type":"CVA",
"RV":30
},
{
"Type":"OpRisk",
"RV":0
}
]}
I save this into a text file called myData.json
In Default.aspx.cs, I have
[WebMethod]
public static String GetDataJSON(){
String myvar = File.ReadAllText("C:\\Users\\Serge\\Downloads\\GoogleChartExample\\GoogleChartExample\\myData.json");
return myvar;
}
I call the function from Java Script in Default.aspx
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'Default.aspx/GetDataJSON',
contentType: 'application/json',
data: {},
async: false,
success:
function (response) {
console.log(response.d);
var data = new google.visualization.DataTable(response.d);
var csv = google.visualization.dataTableToCsv(data);
console.log(csv);
new google.visualization.ColumnChart(document.getElementById('myChart1')).draw(data, { title: "MyChart1" });
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + '\n' + errorThrown);
if (!$.browser.msie) {
console.log(jqXHR);
}
}
});
}
=> console.log(response.d) outputs my JSON string exactly as intended
=> console.log(csv) does not output anything
=> the google chart outputs a red box saying “Table has no columns”
I understand that there are 2 types of JSON format. The one that google has in its example has "cols": [ , and "rows": [ . Does it mean that Google Chart / Dataset is not compatible with my format? Is there anyway for me to convert from one to the other?
Would I be better not to use JSON and export from excel -> cvs => a C# array -> a google dataset?
Thank you very much.
Serge

How to download the file that this file is created in asp.net

My webapplication : I click a button, this button call a web service function, this function create a file(using DocX dll). I want to download this file just created via web browser similar download a file on web.
How to do it?
My code below
// Click button event
$(frm_id+' #btn_eprt_tml')
.button()
.click(function(){
//eprt_tml
$.ajax({
type: "POST",
url: "JqueryFunction.aspx/eprt_tml",
data: "{ptcn_id:'"+ptcn_id+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Completed");
},
error: function () {
alert("Not completed");
}
});
//eprt_tml function
[System.Web.Services.WebMethod]
public static void eprt_tml(int ptcn_id)
{
DocX g_document;
try
{
// Store a global reference to the loaded document.
g_document = DocX.Load(#"D:\Project\CRM1\tml\tml_tpt.docx");
g_document = crt_from_tpl(DocX.Load(#"D:\Project\CRM1\tml\tml_tpt.docx"));
// Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
//g_document.Save();
g_document.SaveAs(#"D:\Project\CRM1\tml\Invoice_The_Happy_Builder.docx");
}
// The template 'Template.docx' does not exist, so create it.
catch (FileNotFoundException)
{
}
}
//crt_from_tpl function
[System.Web.Services.WebMethod]
private static DocX crt_from_tpl(DocX template)
{
template.AddCustomProperty(new CustomProperty("static_title", "afdaslfjlk"));
template.AddCustomProperty(new CustomProperty("tmlname", "asdfasdfasf"));
template.AddCustomProperty(new CustomProperty("tmlcontent", "asdfasd"));
template.AddCustomProperty(new CustomProperty("ptcnname", "asdasdfsd"));
template.AddCustomProperty(new CustomProperty("ptcntitle", "asdfasdfsad"));
template.AddCustomProperty(new CustomProperty("coursename", "asdfsadsdf"));
return template;
}
Create the file name on the basis of SessionID
Replace ur "tml_tpt" to "HttpContext.Current.Session.SessionID"
[System.Web.Services.WebMethod(EnableSession=true)]
public static void eprt_tml(int ptcn_id)
{
DocX g_document;
try
{
// Store a global reference to the loaded document.
g_document = DocX.Load(#"D:\Project\CRM1\tml\tml_tpt.docx");
g_document = crt_from_tpl(DocX.Load(#"D:\Project\CRM1\tml\tml_tpt.docx"));
// Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
//g_document.Save();
g_document.SaveAs(#"D:\Project\CRM1\tml\Invoice_The_Happy_Builder.docx");
}
// The template 'Template.docx' does not exist, so create it.
catch (FileNotFoundException)
{
}
}

Capture data from FORM using jQuery/Ajax/JSON

I have a few textboxes on a form and when the user submits I want to capture the data and insert it into a database.
Here is what my code looks like
// Called just before the form is submitted.
beforeSubmit: function(data)
{
var item = $("[id$='item']");
var category = $("[id$='category']");
var record = $("[id$='record']");
var json = "{'ItemName':'" + escape(item.val()) +
"','CategoryID':'" + category.val() + "','RecordID':'" + record.val() + "'}";
//This page is where data is to be retrieved and processed.
var ajaxPage = "DataProcessor.aspx?Save=1";
var options =
{
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function(response)
{
alert("success: " + response);
},
error: function(msg)
{
alert("failed: " + msg);
}
};
//Execute the Ajax call and get a response.
var returnText = $.ajax(options).responseText;
if (returnText == 1) {
record.html(returnText);
$("#divMsg").html("<font color=blue>Record saved successfully.</font>");
}
else
{
record.html(returnText);
$("#divMsg").html("<font color=red>Record not saved successfully.</font>");
}
// $("#data").html("<font color=blue>Data sent to the server :</font> <br />" + $.param(data));
},
Here is what data is sent to the server: if I uncomment the following line.
// $("#data").html("<font color=blue>Data sent to the server :</font> <br />" + $.param(data));
__VIEWSTATE=%2FwEPDwULLTE4ODM1ODM4NDFkZOFEQfA7cHuTisEwOQmIaj1nYR23&__EVENTVALIDATION=%2FwEWDwLuksaHBgLniKOABAKV8o75BgLlosbxAgKUjpHvCALf9YLVCgLCtfnhAQKyqcC9BQL357nNAQLW9%2FeuDQKvpuq2CALyveCRDwKgoPWXDAKhwImNCwKiwImN &day_fi=12&month_fi=12&year_fi=1234&lastFour_fi=777&countryPrefix_fi=1&areaCode_fi=555-555&phoneNumber_fi=5555&email_fi=nisardotnet%40gmail.com&username=nisarkhan&password=123456&retypePassword=123456
Nisardotnet - are you working in C#? You've got way too much going on here. You can cut down your code by half using web methods - also, get rid of viewstate - you don't need it (remove the form from the page)
If your working in C# let me know and I can help.
Rob
****APPEND****
Ok - I built a simple "grab input values and update DB" thing - it's on my site here.
Give me a shout if you've got any questions.
Rob
****APPEND****
Ok, so in your class file you could have
internal static void updateDB(String values)
{
// do something with 'values'
}
Then in your aspx page you can call it like so...
[WebMethod]
public static void updateDB(String values)
{
yourClass.updateDB(values);
}
That should work.
You should be able to pull it all out of the Request.Form.

Resources