Unable to bind json result to MVC UI - json

I am trying to bind Json result to MVC 4.0 UI (cshtml) but looks like I am missing something...
Below are my controller and CSHtml page code snippet...
Could you please give me some pointers? as what I am missing or doing wrong ?
Please note that I am able to view the Json result (all rows) when I run the application... only thing is that it is not getting displayed per formatting mentioned below.
Sample of Json on UI that is getting displayed.
{"SomeCollection":[{"SequenceID":1,"Name":"test","LastName":"test2","SomeCollection":[]}
Controller
public JsonResult ShowJsonResult()
{
return Json(new { objSrv.SomeCollection }, JsonRequestBehavior.AllowGet);
}
CSHtml page
#model IEnumerable<Models.SmName>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowJsonResult</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//$('#btnGetPersons').click(function ()//{
$.getJSON("/Server/ShowJsonResult", null, function (data) {
var div = $('#ajaxDiv');
div.html("<br/> " + " testing: " + "<br/>");
$.each(data, function (i, item) {
printPerson(div, item);
});
});
//});
});
function printPerson(div, item) {
div.append("<br/>" + "Name: " + item.Name);
$.each(item.Addresses, function (i, addr) {
printAddress(div, addr);
});
}
function printAddress(div, item) {
div.append("<br/>" + " " + "Line1: " + item.Name);
}
</script>
</head>
<body>
<div>
<div id="ajaxDiv"></div>
</div>
</body>
</html>

The problem is with JSON object.The JSON that you have given cannot be parsed properly or not in correct format.Please recheck and try.

Related

Convert Json results into HTML form using ASP.NET Core 5 MVC

I want to display the balance related to a specific card when the Id is being selected from the dropdown select list and show the balance value in [enter image description here][1]input on a form.
But what I am getting is only the JSON results when I am running the program. my form is not appearing
The Test action in the controller:
public IActionResult Test()
{
var data = from als in ctx.TbIstanbulCards select new { als.IstanbulCardId, als.Balance };
return Json(data.ToList());
}
The Index view (Test)
#model VmIstanbul
#section Scripts{
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
var options = {};
options.url = "/Customer?handler=SelectAll";
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
data.forEach(function (element) {
$("#customerid").append("<option>
"
+ element.IstanbulCardId + "
</option > ");
});
};
options.error = function () {
$("#msg").html("Error while
making Ajax call!");
};
$.ajax(options);
});
$("#customerid").change(function () {
var options = {};
options.url = "/Customer/" +
$("#customerid").val() + "?handler=SelectByID";
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
$("#companyname").val(data.Balance);
//$("#contactname").val(data.contactName);
//$("#country").val(data.country);
};
options.error = function () {
$("#msg").html("Error while making Ajax call!");
};
$.ajax(options);
});
</script>
}
<form id="myForm" asp-controller="Customer" asp-action="Test">
<label for="departmentsDropdown"><b>Card</b></label>
<select class="form-control" onchange="getValue()" id="departmentsDropdown" name="departmentsDropdown"></select><br />
<input type="text" value="" id="show" />
</form>
The result appear like that
https://i.stack.imgur.com/sqDVl.png
It is not clear from your codes, since the ajax url is razor page route but not mvc. Do you enable both of them?
Besides, from your previous post I see that the View name is Test.cshtml, while the Test action return Json, so when you access /Custom/Test, you just get the Json results instead of a View.
If the Test action is used to display the html view, I think it should return View:
public IActionResult Test()
{
return View();
}
Update:
Have an action(Test) to return View(Test.cshtml). Just reutn View() without any data since I didn't see any place you use the model(VmIstanbul) value in your view.
public IActionResult Test()
{
return View();
}
Have another action to return data to ajax, Give it a name except Test. For example:
public IActionResult TestSelect()
{
var data = from als in ctx.TbIstanbulCards select new { als.IstanbulCardId, als.Balance };
return Json(data.ToList());
}
And change the ajax url to TestSelect
#section Scripts{
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Customer/TestSelect",
success: function (data) {
console.log(data);
var s = '<option value="-1">Please Select a Card id</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].balance + '">' + data[i].istanbulCardId + '</option>';
}
$("#departmentsDropdown").html(s);
}
})
})
function getValue() {
var myVal = $("#departmentsDropdown").val();
$("#show").val(myVal);
}
</script>
}
Result:

when express use view engine, pass a html string,how to make it render to html

I want to imitate jekyll,build a blog with nodejs and express; I use the fs module read the markdown file and translate into html string;then I use res.render('view',{html:html}) to pass my html string ,but in the end it render as text,how can I do? render it into html..
router.get('/:year/:month/:day/:title', function (req, res) {
var fileName =
'../blogs/' +
req.params.year + '-' +
req.params.month + '-' +
req.params.day + '-' +
req.params.title + '.md';
fs.readFile(fileName, 'utf-8',function (err, data) {
if (err) res.send(err);
h=md2html.toHTML(data);
console.log(h);
res.render('blog',{h:h});
});
});
blog.ejs:
<html>
<head>
<title>lla</title>
<meta charset='utf-8'>
</head>
<body>
<%=h%>
</body>
<html>
the result:

How to convert the returned XML to HTML?

I created a simple web service in ASP.net that does some operations:
[WebMethod]
public int Area(int l, int b)
{
return l * b;
}
[WebMethod]
public int Perimeter(int l, int b)
{
return 2 * (l +b);
}
and i called it in HTML file, like:
<html>
<head>
<title>WebService Call using HTTP POST</title>
<body>
<form action="http://localhost:56472/WebSite2/Service.asmx/Area" method="POST">
<input name="l">
<input name="b">
<input type="submit" value="Click for Area">
</form>
<form action="http://localhost:56472/WebSite2/Service.asmx/Perimeter" method="POST">
<input name="l">
<input name="b">
<input type="submit" value="Click for Perimeter">
</form>
</body>
</head>
</html>
put this when i click for the result it will be returned as XML:
<?xml version="1.0" encoding="UTF-8"?>
<int xmlns="http://tempuri.org/">30</int>
And what I want is i want the result in HTML not XML, how to do this?
Can someone help, please?
Thank You :)!
You'll need to call the service via ajax call and use the response to populate the required tag in the HTML.
Check the code below, it's simple jQuery AJAX call,
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
method:"post",
data: {
l: "custom value",
b: "custom value",
}
success: function (data) {
console.log(data.length);
var xmlDoc = $.parseXML(data);
var jXml = $(xmlDoc);
var value = jXml.find("int").text();
$("#result").text(value);
},
failure: function (err) {
console.log("could not call the service : " + err);
}
});
Couple of things to keep in mind
Form submission will take you to next page and destroy Javascript context, that's why we need AJAX call which will just bring us the result from teh service without navigating away from the page.
As server is returning data in XML you'll have to parse it either as XML document or as plain string to get the required values.
***Edited to add
Check out the complete example below.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
<!-- create the function to call on click of a button -->
function getData() {
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
type: 'GET',
dataType: "xml",
data: {
l: "custom value",
b: "custom value"
},
success: function(data) {
console.log("success " + data);
console.log(data.getElementsByTagName("int"));
var xmlDoc = data;
if(typeof(data) === "string") {
xmlDoc = $.parseXML(data);
}
var value = xmlDoc.getElementsByTagName("int")[0].textContent;
$("#result").text(value);
},
error: function(err) {
console.log("error " + JSON.stringify(arguments));
}
});
}
</script>
</head>
<body>
<!-- see the onclick attribute, you have to call your Javascript function in it's value -->
<button onclick="getData();">click to get data</button>
<!-- tag where it result will be displayed -->
<h1 id="result">No result yet</h1>
</body>
</html>

Can't use the data I fetch from parse.com

I have created a simple program to illustrate my problem.
I have a custom class called TestDate which has 2 columns and the default columns one column is a string called val the is a date column called date.
I create a row and set 'date' to new Date('1st April 2013') and I set 'val' to 'First String'
Then I saved it and it saves ok.
Next I retrieve the row using fetch I am able to display the record in the console window of the browser by using JSON.stringify(result)
If though I try to access specific values with JSON.stringify(result.results) I get undefined.
I have tried JSON.parse that hasn't worked I have also tried to access other data in the result object without any success.
It's as if the retrieved data has to converted somehow to be proper json but I do not know how? This is the problem.
my code is shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date Test</title>
</head>
<body>
<button onclick="fetch()">Fetch</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//www.parsecdn.com/js/parse-1.5.0.min.js"></script>
<script>
(function() {
Parse.initialize($PARSE_APPLICATION_ID, "$PARSE_JAVASCRIPT_KEY");
var TestDate = Parse.Object.extend("TestDate");
var testDate = new TestDate();
testDate.set({
'date': new Date('2013, 4, 1'),
'val': 'First String'
}).save(null, {
success: function(result) {
console.log("Inside create: success: result: " + JSON.stringify(result));
// Result in browser console is:
// Inside create: success: result:
// {"date":{"__type":"Date","iso":"2013-03-31T23:00:00.000Z"},
// "val":"First String","objectId":"Nq2PmNH0yN",
// "createdAt":"2015-09-14T09:04:58.487Z",
// "updatedAt":"2015-09-14T09:04:58.487Z"}
},
error: function(obj, error) {
console.log("Inside create: error: obj: " + JSON.stringfify(obj) +
" error: " + JSON.stringify(error));
}
});
}());
function fetch() {
var TestDate = Parse.Object.extend("TestDate");
var testDate = new TestDate();
testDate.fetch({
success: function(result) {
console.log("Inside fetch: success: result: " + JSON.stringify(result));
// Result in browser console is:
// Inside fetch: success: result:
// {"results":[{"createdAt":"2015-09-14T09:04:58.487Z",
// "date":{"__type":"Date","iso":"2013-03-31T23:00:00.000Z"},
// "objectId":"Nq2PmNH0yN","updatedAt":"2015-09-14T09:04:58.487Z",
// "val":"First String"}]}
console.log("Inside fetch: success: result.results: " + JSON.stringify(result.results));
// The result in the browser shows the problem I get back undefined:
// Inside fetch: success: result.results: undefined
},
error: function(obj, error) {
console.log("Inside fetch: error: obj" + JSON.stringify(obj) +
" error " + JSON.stringify(error));
}
})
}
</script>
</body>
</html>
var date = result.get("date");
var val = result.get("val");
or
var date = result.attributes.date;
var val = result.attributes.val;

Load json data into the factory file

I am new to AngularJS and just started learning it. How can I load the JSON file into the script.js file without directly adding the entire data.
Here is the code of the program:
<!DOCTYPE html>
<html ng-app="quizApp">
<head>
<meta charset="utf-8" />
<title>QuizApp</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<h1 class="title">QuizApp</h1>
<quiz/>
</div>
</body>
Plunkr.
You need to correct the json pasted in ques.json (by using quotes "") otherwise if you will invoke $http.get() then you will get exception due to invalid json.
Once you will correct the json content in ques.json then just use $http and assign the result to questions variable.
E.g.
app.factory('quizFactory', function($http) {
var questions = [];
$http.get('ques.json').success(function(data) {
questions = data;
})
return {
getQuestion: function(id) {
if(id < questions.length) {
return questions[id];
} else {
return false;
}
}
};
});
Here is the demo
$http.get('ques.json')
.then(function(result){
$scope.questions = result.data;
});