How to read value when using model.save() or fetch()? - asp.net

Man = Backbone.Model.extend({
url:'/test.aspx',
initialize: function(){
},
defaults: {
name:'Jim',
age: '38'
},
validate:function(attributes){
if(attributes.name == '') {
return "name can't be null";
}
}
});
var man = new Man;
man.set({name:'the5fire'});
man.save(); //the format is json{"name":"the5fire","age":38}
In test.aspx.cs, how can I read this value {"name":"the5fire","age":38} ?
I have tried Request.Form.ToString() but found no data there.
Chrome developer tools shows this json-format data in the "request payload" block.
update:
If I use man.fetch({ data: { Pagesize: '1', PageIndex: '111' } ), then on the server side, I can use Request.Params["PageIndex"]. But how can I get the name? the age?

You can access the raw body of the request via HttpRequest.InputStream and convert it to a string :
string jsonstring = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
You would then deserialize this string to get an object, for example:
using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(jsonstring);
string name = (string)d["name"];

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);
}
);
}

MeteorJS: CALLBACKS

PROBLEM: I want to parse the elements in a page from another website, glue resulting elements in an object and insert it in a Mongo collection. Before insertion i want to check if my Mongo yet has an identical object. If it does it shall exit the running functions, otherwise i want the script to start parsing the next target.
Example:
I have a function that connects to a webpage and returns its body content
It is parsed
When <a></a> elements are met, another callback is called in which all parsed elements are merged in one object and inserted in a collection
My code :
var Cheerio = Meteor.npmRequire('cheerio');
var lastUrl;
var exit = false;
Meteor.methods({
parsing:function(){
this.unblock();
request("https://example.com/", Meteor.bindEnvironment(function(error, response, body) {
if (!error && response.statusCode == 200) {
$ = Cheerio.load(body);
var k = 1;
$("div.content").each(function() {
var name = $...//parsing
var age = $....//parsing
var url = $...//parsing <a></a> elements
var r = request("https://example.com/"+url, Meteor.bindEnvironment(function(error, response, body) {
lastUrl = response.request.uri.href;// get the last routing link
var metadata = {
name: name,
age: age
url: lastUrl
};
var postExist;
postExist = Posts.findOne(metadata); // return undefined if doesnt exist, AND every time postExist = undefined ??
if (!postExist){
Posts.insert(metadata);// if post doesnt exist (every time go here ??)
}
else {
exit = true; // if exist
}
}));
if (exit === true) return false;
});
}
}));
}
});
Problem 1 : The problem is my function works every time, but it doesn't stop even if the object exists in my collection
Problem 2 : postExist is always undefined
EDIT : The execution must stop and wait until the second request's response.
var url = $...//parsing <a></a> elements
//STOP HERE AND WAIT !!
var r = request("https://example.com/"+url, Meteor.bindEnvironment(function(error, response, body) {
Looks like you want the second request to be synchronous and not asynchronous.
To achieve this, use a future
var Cheerio = Meteor.npmRequire('cheerio');
var Future = Meteor.npmRequire('fibers/future');
var lastUrl;
var exit = false;
Meteor.methods({
parsing:function(){
this.unblock();
request("https://example.com/", Meteor.bindEnvironment(function(error, response, body) {
if (!error && response.statusCode == 200) {
$ = Cheerio.load(body);
var k = 1;
$("div.content").each(function() {
var name = $...//parsing
var age = $....//parsing
var url = $...//parsing <a></a> elements
var fut = new Future();
var r = request("https://example.com/"+url, Meteor.bindEnvironment(function(error, response, body) {
lastUrl = response.request.uri.href;// get the last routing link
var metadata = {
name: name,
age: age
url: lastUrl
};
var postExist;
postExist = Posts.findOne(metadata); // return undefined if doesnt exist
if (!postExist) {
Posts.insert(metadata);// if post doesnt exist (every time go here ??)
fut.return(true);
} else {
fut.return(false);
}
}));
var status = fut.wait();
return status;
});
}
}));
}
});
You can use futures whenever you can't utilize callback functions (e.g. you want the user to wait on the result of a callback before presenting info).
Hopefully that helps,
Elliott
This is the opposite :
postExist = Posts.findOne(metadata); // return undefined if doesnt exist > you're right
if (!postExist){ //=if NOT undefined = if it EXISTS !
Posts.insert(metadata);
}else {
exit = true; // if undefined > if it DOES NOT EXIST !
}
You need to inverse the condition or the code inside

Jquery Datatables Ajax Response

I am trying to follow the datatable example for Ajax data source (objects) found here. I am using asp.net and have the following handler which receives my data, processes it and provides the response.
public class UsersHandler : IHttpHandler
{
private const string JsHeader = #"{{""data"" {0}}}";
public void ProcessRequest(HttpContext context)
{
IEnumerable<SystemUser> data = SystemUserLogic.LoadAllSystemUsers();
List<SimpleUser> userlist = new List<SimpleUser>();
foreach (SystemUser su in data)
{
SimpleUser simple = new SimpleUser();
simple.Id = su.Id;
simple.FullName = su.NameFirst;
simple.Email = "example#email.co.uk";
userlist.Add(simple);
}
string json = JsonConvert.SerializeObject(userlist, Formatting.Indented);
context.Response.ContentType = "text/plain";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetNoStore();
context.Response.Expires = -1;
context.Response.Write(String.Format(JsHeader, json));
}
which deliveries the correct response when I catch it in the browser and look at the data via the network traffic. My aspx page contains the following.
$('#table_id').DataTable({
"ajax": '/Handlers_New/UsersHandler.ashx',
"columns": [
{ "data": "Id" },
{ "data": "FullName" },
{ "data": "Email" },
{ "data": "KeyResource" }
]
});
However when the page loads, I am getting this error:
DataTables warning: table id=table_id - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
The outputted data looks like this,
{"data" [
{
"Id": 1,
"FullName": "Admin",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 2,
"FullName": "Jon",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 3,
"FullName": "Stephen",
"Email": "example#email.co.uk",
"KeyResource": false
}, etc.....
Please tell me why I am getting this error. Should I be manipulating the json object differently, or am I missing something with the Jquery datatables?
I have managed to fix my issue amazingly due to jsonlint. I ran my code through that and it turns out I was missing a ':' in my jsHeader. So what I had was:
private const string JsHeader = #"{{""data"" {0}}}";
and what I have now which now works is:
private const string JsHeader = #"{{""data"": {0}}}";
Hope this helps any one else encountering a similar issue.

how to use highcharts in asp.net MVC 4

I'm new in highcharts. I try to use it in my asp.net MVC 4 project. I want to pass information relative to charts from controller to view. I've used session to pass differents categories, the chart appear but without categories. Is there any solution to pass information from controller to view?
this is part of my code:
view:
<script type="text/javascript">
$(function () {
$('#divStat').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Historic World Population by Region'
},
subtitle: {
text: ''
},
xAxis: {
categories: '#Session["affiche"]',
title: {
text: null
}
},
[...]
});
</script>
controller:
public ActionResult Stat()
{
String[] list = new String[5];
list[0] = "Africa";
list[1] = "America";
list[2] = "Asia";
list[3] = "Europe";
list[4] = "Oceania";
Session["affiche"] = list;
return PartialView("Charts");
}
You have to put "," among the strings to make javascript understand that is an array
#{
string[] theList = (string[])Session["affiche"];
string javascriptArrayString = "";
foreach(string str in theList){
javascriptArrayString += "'"+ str +"',";
}
javascriptArrayString = javascriptArrayString.Substring(javascriptArrayString.Length,javascriptArrayString.Length-1);
}
then:
categories: [#javascriptArrayString],
and the html result will be like :
categories: ['Africa','Asia','America','Europe','Oceania'],
this is a bit rough coding , but i think you'll get the point.

Kendo UI adding row at Runtime(Client Side)

I am able to add a row at runtime using .js file into Kendo Data Source, but I havent seen from the form(UI), I followed the below steps
var vgrid = $("#grdEntitys").data("kendoGrid");
var datasource = vgrid.dataSource;
var newRecord = { No: "8164",ModellNo: "147",ID: "Test01", Name: "TEST"}
datasource.insert(newRecord);
then It throws an error "TypeError: Cannot read property 'AttributeValue' of undefined",
if we look at the console log, I am able to see the incrmented rows count as well as the newly inserted record. But in UI there is no change(UI Grid).
could you please anyone let me know, how to add row at client side?
Thanks in advance
For insert you have to specify index (Insert) :
var dataItem = dataSource.insert(0, { name: "John Doe" });
Alternatively you could use Add where you don't have to specify the index:
<script>
var dataSource= new kendo.data.DataSource({
data: [
{ name: "Jane Doe", age: 30 }
]
});
dataSource.add({ name: "John Doe", age: 33 });
you can use the script in you event to add item in your grid.
var dataSource = $("#CustomerPackageChannelKendoGridAdd").data("kendoGrid").dataSource;
// Get value from another field
var _JV_ACCOUNT_ID = $('#JV_ACCOUNT_ID').val();
var _JV_ACCOUNT_NAME = $('#JV_ACCOUNT_NAME').val();
var _JV_ACCOUNT_CODE = $('#JV_ACCOUNT_CODE').val();
var _JV_NOTES = $('#JV_NOTES').val();
var _JV_DATE = $('#JV_DATE').val();
var type = $('#JV_Transaction_TYPE').val();
// You can set condition if required for you
if (CheckExistingData(gridDataAdd, _JV_ACCOUNT_ID) == false) {
currentId += 1;
dataSource.add(
{
id: currentId,
JV_ACCOUNT_ID: _JV_ACCOUNT_ID,
JV_ACCOUNT_NAME: _JV_ACCOUNT_NAME
, JV_ACCOUNT_CODE: _JV_ACCOUNT_CODE
, JV_NOTES: _JV_NOTES
, JV_DATE: _JV_DATE
, JV_DEBIT_AMOUNT: _JV_DEBIT_AMOUNT
, JV_CREDIT_AMOUNT: _JV_CREDIT_AMOUNT
});
}
For more you can also see this:

Resources