Json Query not displaying correctly in MCV - c#

I am currently trying to pass data from a controller to a view to display a pie Chart. But instead of a Pie Chart the webpage is only displaying the string as shown below. How can I get this to show the Pie Chart and not the string
Controller Code
c#
public ActionResult Index()
{
return Json(Result(), "text/plain",JsonRequestBehavior.AllowGet);
}
View Code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=utf-8; charset = utf - 8",
cache: false,
url: '#Url.Action("Index", "Home")',
success: function (result) {
console.log(result);
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(function () {
drawChart(result);
});
}
});
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Marks Obtained');
var dataArray = [];
$.each(result, function (i, obj) {
dataArray.push([obj.stdName, obj.marksObtained]);
});
data.addRows(dataArray);
var columnChartOptions = {
title: "Students Performance",
width: 1000,
height: 400,
bar: { groupWidth: "20%" },
};
var columnChart = new google.visualization.PieChart(document
.getElementById('piechart_div'));
columnChart.draw(data, columnChartOptions);
}
</script>
</head>
<body>
<div id="piechart_div"></div>
The strange thing is that I downloaded an example, which works fine, and I set up a new MCV project and added the code exactly the same, but my project shows the string, while the project I downloaded will display the pie chart with no problems. I am really confused as to why this is happening

Related

Is it possible to create document libraries in SharePoint Online in code using Rest API?

Is it possible to create document libraries in code using the Rest API? and if so how?
I've created folders and files etc through the rest API but cannot find anything on creating document libraries
I am assuming that it wouldn't be too dissimilar to creating a folder if its possible
Sample code for your reference.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
function createNewLibraryByRest() {
var newListName = "RestApiLib";
var listEndPoint = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/";
$.ajax({
url: listEndPoint,
method: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.List' },
'AllowContentTypes': true,
'BaseTemplate': 101, //101 for document library
'ContentTypesEnabled': true,
'Description': 'Description',
'OnQuickLaunch': true,
'Title': newListName
}),
headers: {
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('Library Created!');
},
error: function (err) {
alert(err.responseText);
}
});
}
</script>
<input id="Button1" type="button" onclick="createNewLibraryByRest()" value="createNewLibraryByRest" />

Autocomplete does not showing the results from controller in asp.net MVC

The autocomplete code written is getting the results from controller and is also showing when used F12 developer network tab with the browser. But the actual returned result is not showed by the textbox, only drop-down with no values are shown.
I'm including the codes of view and controller. Please help me out to solve this.
code of the view page :
<html>
<head><title></title>
<link href="~/Content/themes/base/jquery.ui.autocomplete.css" rel="stylesheet" />
<script type="text/javascript" >
$(document).ready(function () {
alert("hi");
$("#ValueField").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Customer/AutoretrieveCustomer",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
var items = $.map(data, function (item) {
return {
label: item.FirstName,
value: item.FirstName
};
});
response(items);
}
})
}
});
});
</script>
</head>
<body>
<div id="CusView">
<label for="FirstName">Enter Customer First name : </label>
Enter value : <input type="text" id="ValueField" />
</div>
</body>
</html>
code of the controller :
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AutoretrieveCustomer(string term)
{
Banking.BankingDBEntities db = new BankingDBEntities();
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Also I would need the code for getting the id of the user selected item in the textbox.
The following the output pic when the autocomplete is executed
This bit in your controller action:
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
Means that your controller action is actually returning an array of strings, not an array of objects like your success function is assuming.
You should be able to remove the mapping and just call response directly with the array of strings:
success: function (data) {
response(data);
}
Or, just:
success: response

Making an Ajax call to a partial view after ajax success

I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.
If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});

How to make javascript execute after using jQuery to dynamically load user control to div?

I have a Web User Control with javascript and css blocks. I'm using jQuery to dynamically load it into the main page. How do I make the alert('haha') to execute when the user control is loaded into the div called "divTable"?
In my .ascx file, I have
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
</script>
In the .aspx file, I have
<script type="text/javascript">
$(function () {
$('button').click(GetTable);
});
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
</script>
In the .svc file, I have
[OperationContract]
public string RenderUC(string path, string id1, string id2)
{
Page pageHolder = new Page();
var viewControl = (ParameterizedTableControl)pageHolder.LoadControl(path);
viewControl.ID1= id1
viewControl.ID2 = id2;
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, true);
return output.ToString();
}
Any javascript that you want to run once the ajax operation is complete should go in the success handler.
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
//
// insert whatever you want here
//
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
You can call your function inside your <script> block in the ascx control like this:
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
pageLoad();
</script>
This will make your script run when the browser renders your script tag.

ASP.NET MVC3 and jquery form plugin

I'm using ASP.NET MCV3, jquery 1.5.2 and jquery form plugin.
Here's the sample code:
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function () {
$('#uploadForm').ajaxForm({
dataType: 'json',
beforeSubmit: function () { alert('beforeSubmit'); },
success: function() { alert('success'); },
error: function () { alert('error'); }
});
});
</script>
<form id="uploadForm" action="#Url.Action("UploadFile")" method="post">
<input type="submit" value="Submit file" />
</form>
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult UploadFile()
{
return Json(new { message = "success" });
}
When I submit the form, I always get the following error message: Expected ';'
I searched SO, Google.. but couldn't find any solution to this problem.
I found Darin's comment here, but I need to have beforeSubmit and success events.
Any help would be greatly appreciated!
I changed dataType from json to text and then I parsed the result. Everything seams to work ok.
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function () {
$('#uploadForm').ajaxForm({
dataType: 'text',
beforeSubmit: function () { alert('beforeSubmit'); },
success: processJson,
error: function () { alert('error'); }
});
});
function processJson(responseJson) {
var obj = jQuery.parseJSON(responseJson);
alert(obj.message);
}
</script>

Categories

Resources