I have a textarea on my html page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSquareNumbers").click(function () {
var Calculate = $("#txtString").val();
//Calculate = $("#txtString") //.Replace("<br/>", ",").TrimEnd(',')
$.ajax({
url: "/api/SquareNumbers/SquareNums/",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Calculate),
success: function (result) {
$("#txtResult").val(result);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
$("#txtResult").val(err.Message)
}
});
});
});
</script>
</head>
<body>
<textarea id="txtString" cols=50 rows="15"></textarea><br>
<input type="button" value="Square All Numbers" id="btnSquareNumbers"><br>
<output type="text" id="txtResult" disabled />
</body>
</html>
It will accept a vertical list of numbers e.g.
2
5
8
13
I need to send this to the C# controller, square each number and display the results on the web page.
When I run the code, it truncates the numbers and gives 25813 squared!
I am new to this... any advice?
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace ReturnMultilineText.Controllers
{
public class SquareNumbersController : ApiController
{
[HttpPost]
public List<int> SquareNums([FromBody]string Calculate)
{
List<string> caseList = txtString.Split().ToList();
List<int> intList = caseList.ConvertAll(int.Parse);
List<int> ans = new List<int>();
for (var i = 0; i < intList.Count; i++)
{
ans.Add((intList[i] * intList[i]));
}
return ans;
}
}
}
Input:
1 2 3 4
2 3 4
Gives Output:
1,4,9,16,1,4,9
I am nearly there now.... Need to find the linefeed... does stringify remove it? and replace it with a space?
GOT THE SOLUTION... just needed to split by "\n"...
string[] textList = Calculate.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
Cheers for the help and advice.
Related
what i want to do is creating charts from excuted data from a query in asp.net core but i face problem in usnig [httppost] in the controller when i use it gives me error 405 and when i don't use it the json data appear in the view and below are my codes.
Hello, what i want to do is creating charts from excuted data from a query in asp.net core but i face problem in usnig [httppost] in the controller when i use it gives me error 405 and when i don't use it the json data appear in the view and below are my codes.
public JsonResult Index()
{
string query = "select UserId, count(ServiceOrderNumber) as OrderNum from [dbo].[ServiceOrders] group by [UserId] order by count ([ServiceOrderNumber]) desc";
string constr = this._configuration.GetConnectionString("DefaultConnection");
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"UserId", "OrderNum"
});
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["UserId"], sdr["OrderNum"]
});
}
con.Close();
return Json(chartData);
}
and my view is
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Reports/Index/",
contentType: "application/json; charset=utf-8",
cache: false,
traditional: true,
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
//Pie
var options = {
title: 'USA City Distribution'
};
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 500px; height: 400px;">
</div>
</body>
</html>
i face problem in usnig [httppost] in the controller when i use it
gives me error 405
The address bar of browser only support Get request.If you send the post request in browser address bar,it will get http 405 method not allowed error.
when i don't use it the json data appear in the
view and below are my codes.
If you remove HttpPost,it will be HttpGet by default.So when you enter the url in address bar,you will get the json string.
Also you may misunderstand ajax,ajax will be sent after your view has loaded.
You could check the document:
AJAX is a developer's dream, because you can:
Request data from a server - after the page has loaded
So,what you need do first is to send get request to backend to load the view and then it will hit the ajax you wrote. The whole principle you could check the gif below.
Here is a whole working demo:
Index.cshtml View in Views/Reports folder:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script> //be sure add jquery....
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "/Reports/Index/",
//url:"/Reports/GetJson/" //if you do not use route attribute in action
contentType: "application/json; charset=utf-8",
cache: false,
traditional: true,
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r);
//Pie
var options = {
title: 'USA City Distribution'
};
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 500px; height: 400px;">
</div>
</body>
</html>
Controller:
public class ReportsController : Controller
{
//default is httpget
public ActionResult Index()
{
return View(); //it is used to load the view..
}
//if your request url is the same with get method,you could add route attribute.
//Because the controller could not have two same name method with the same parameter although they are used in different http request
[Route("Reports/Index")]
[HttpPost]
public JsonResult GetJson()
{
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"UserId", "OrderNum"
});
chartData.Add(new object[]
{
"1", 3
});
chartData.Add(new object[]
{
"2", 4
});
chartData.Add(new object[]
{
"3", 6
});
return Json(chartData);
}
}
Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Result:
I create example method for throw the error.
Code behind (.aspx.cs):
public partial class Test1 : System.Web.UI.Page
{
[WebMethod]
public static int Medthod1()
{
int data = 1;
try
{
data = data / (data - 1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); // Attempted to divide by zero.
throw;
}
return 1;
}
}
I call the method by jQuery.ajax and alert the output error.
Inline Code (.aspx):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test1</title>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#button1").on("click", function (event) {
$.ajax({
type: "POST",
url: "Test1.aspx/Medthod1",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status, xhr) {
alert(result.d);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
alert(xhr.responseText.Message);
}
});
});
});
</script>
</head>
<body>
<button type="button" id="button1">Button 1</button>
</body>
</html>
Output from the line alert(xhr.responseText);:
{"Message":"Attempted to divide by zero.","StackTrace":" at Test.Test1.Medthod1() in C:\\Project\\Test\\Test\\Test1.aspx.cs:line 29","ExceptionType":"System.DivideByZeroException"}
Output from the line alert(xhr.responseText.Message);:
undefined
However, my output expectation is only:
Attempted to divide by zero.
The response you received was just a string. So, you need to parse it to an object before assigning.
var responseText = '{"Message":"Attempted to divide by zero.","StackTrace":"...","ExceptionType":"System.DivideByZeroException"}';
console.log(JSON.parse(responseText).Message);
// in your case, it should be:
// alert(JSON.parse(xhr.responseText).Message);
More information: JSON.parse()
how can i export an image from DB - Sqlite and display this image in the view?
im using angular code, and the images byte stored now in x.img var.
i want to display the image in img tag.
i tried few ways...
please your help.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link href="~/Content/productmenuStyle.css" rel="stylesheet" />
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module("myCode", []);
app.controller("CodeController", function ($scope, $http) {
$scope.Table = false;
$scope.showProduct = function (num) {
$scope.number = num;
$scope.getProduct(num);
}
$scope.getProduct = function (num) {
var list = $http({
method: 'post',
url: 'getProductjson',
params: {
prClass: num
}
});
list.then(function (list) {
$scope.Products = list.data;
}, function () {
alert("Inavalid data !!!");
});
}
$scope.sendProduct = function (num) {
var list = $http({
method: 'post',
url: 'sendProduct',
params: {
pid: num,
}
});
list.then(function (list) {
alert("The Product Addad To The Cart");
}, function () {
alert("Inavalid data !!!");
});
}
});
</script>
</head>
i have WebService that get 2 string and return if they equals
WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "Validate the login credentials")]
public bool Validate(string UserName, string Password)
{
if (Password == "test" && UserName == "test")
return true;
else
return false;
}
}
and i have html page that call this WebService and need to return the Result
<html lang="en-US">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var Surl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
$(document).ready(function () {
$("input#submit").click(function (event) {
//var uid = document.getElementById("UserName").value;
//var pwd = document.getElementById("Password").value;
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
$.ajax({
ServiceCallID: 1,
url: Surl,
type: 'POST',
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
returnVal = result.d;
alert(returnVal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
returnVal = '';
}
});
});
});
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" />Connet to my WS
</form>
</body>
</html>
this what i get:
and i try this, still same problem....
<script>
function XX() {
alert("in");
$.post('http://localhost/WS_HTML/Service1.asmx/Validate', { username: 'test', password: 'test' }, function (response) {
response; // Here is response
alert(response);
});
}
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" onclick="XX();" />Connet to my WS2
</form>
</body>
</html>
i try with $.get - and same.... Nothing happens....
from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,
but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>
Request format is unrecognized for URL unexpectedly ending in '/Validate'.
I swear to God that for several days I break my head and can not figure out why it does not work
):
thanks,
You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)
Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).
<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript">
var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
function submitMyForm(){
// Define your datas
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
// Create and send the request
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
// Log with console.log() or alert if you want...
console.log('State of my request changed! ');
if (XMLHttpRequest.DONE === request.readyState) {
console.log(request.responseText);
}
}
request.open('POST', myUrl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
</script>
</head>
<body>
<form>
<button onclick="submitMyForm()" >Connect to my WS</button>
</form>
</body>
</html>
I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).
For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.
I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).
Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum
Hope I help you.
Why not use $.post() ?
$.post('/your/service/url/', {username:'asd', password:'qwe'}, function(response){
response; // Here is response
});
Me and ASMX web services do not get on. We argue. She brings up arguments we had in the past. It's a pain. Our relationship is on the rocks!
I have an ASMX web service, which I haven't serialised with the Newtonsoft library (as explained why here: http://encosia.com/2011/04/13/asp-net-web-services-mistake-manual-json-serialization/). It looks like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
var dict = AtomicCore.CityObject.GetCitiesInCountryWithStateAutocomplete(isoalpha2, prefixText);
string[] cities = dict.Values.ToArray();
return cities;
}
Simple enough right? It return this when searching for new:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<string>New Orleans, Louisiana</string>
<string>New York, New York</string>
</ArrayOfString>
I was expecting JSON, but after a bit of reading, it seems I shouldn't try and serialise the output - it should just happen right? Anyway, so I have the following JQuery on the frontend:
$('#<%=txtCity.ClientID%>').autocomplete('<%=ResolveUrl("~/AtomicService/Assets.asmx/GetCitiesWithState")%>', {
dataType: 'json',
httpMethod: 'POST',
contentType: 'application/json; charset=utf-8',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.d.length; i++) {
rows[i] = { data: data.d[i], value: data.d[i].Value, result: data.d[i].Value };
}
return rows;
},
formatItem: function (row, i, n) {
return row.Value;
},
extraParams: {
minChars: 2,
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
maxRows: 20,
prefixText: function () {
return $('#<%=txtCity.ClientID%>').val()
}
},
max: 20
}).result(function (event, data, formatted) {
if (data) {
alert(data['Key']);
}
});
I can see the calls using Chrome:
And yet stuff all happens! There is no Jquery errors, no fireworks, no anything. She is ignoring me.
At first I was blaming the webservice, but I think this may have more to do with how I'm parsing and formatting the data in jquery.
So, my question is, what am I doing wrong and how can I make the autocomplete work correctly?
Help appreciated :)
EDIT: It may not be helpful, but this is what I see in Fiddler:
The jQuery UI autocomplete does not anymore use the formatItem method. That and many other such methods were present in autocomplete's earlier version that was a plugin here
I have rewritten your code using the jQuery UI's autocomplete and it works for me with the below htm and asmx files.
Refer to the demos on the jQueryUI autocomplete for more methods you could use.
I have used the json2.min.js from www.json.org
Also I have added the [System.Web.Script.Services.ScriptService] attribute to the Service1 class so that it could directly be invoked from jQuery as a json web service.
These articles helped me:
ASMX and JSON – Common mistakes and misconceptions
Using jQuery to Consume ASP.NET JSON Web Services
3 mistakes to avoid when using jQuery with ASP.NET AJAX
The htm file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery to ASMX</title>
<link rel="Stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/cupertino/jquery-ui.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://localhost/Scripts/json2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#txtInput").autocomplete({
source:function (request, response) {
var paramters = {
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
prefixText: request.term
};
$.ajax({
url: 'Service1.asmx/GetCitiesWithState',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramters),
success: function(data) {
response($.each(data.d, function(index, value) {
return {
label: value,
value: index
}
}));
}
});
},
minLength:2,
delay:500
});
});
</script>
<p>
Hello, World!</p>
<label for="txtInput">
Enter the string here:</label><input type="text" id="txtInput"/>
</body>
</html>
The asmx file
using System.Web.Script.Services;
using System.Web.Services;
namespace jQueryAutoCompleteBackEnd
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service1 : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
return new string[] { "New Orleans, Lousiana", "New York, New York" };
}
}
}
The reason that the asmx webmethod is returning XML rather than JSON is because the HTTP method is GET rather than POST.
In order for the autocomplete plugin to use POST you'll have to implement the source parameter using a callback function, see here