How to display data from server in textarea - javascript

I have below code in C# which adds data in Dictionary
public static Dictionary<int, string> ReadFile()
{
Dictionary<int, string> datalist = new Dictionary<int,string>();
var lines = File.ReadAllLines(#"C:\\temp\\Sample.txt");
int i = 1;
foreach (var line in lines)
{
datalist.Add(i, line);
i++;
}
return datalist;
}
Now, I want to display Dictionary data separated by key line by line in textarea. Below is my UI code
<button type="button" id ="GetFlatFile">Click Me!</button>
<div id ="DisplayFlatFile">
</div>
function GetFlatFileAndSetupColumn() {
$("#GetFlatFile").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/ReadFile",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (jsondata) {
mydata = jsondata.d;
$('#DisplayFlatFile').empty();
$('#DisplayFlatFile').append(mydata);
}, error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
});
}
How to do it?

First, GetFlatFile is not a <textarea> element, it's <div> element. Assumed that jsondata.d contains dictionary values returned from code-behind method, you can use jQuery.each() to iterate values:
function GetFlatFileAndSetupColumn() {
$("#GetFlatFile").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/ReadFile",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (jsondata) {
mydata = jsondata.d;
$('#DisplayFlatFile').empty();
// iterate keys and values here
$(mydata).each(function (key, value) {
// data display example
$('#DisplayFlatFile').append(key + ' - ' + value);
// line break per iteration
$('#DisplayFlatFile').append('<br />');
});
}, error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
});
}
Additionally, your code-behind method should be marked with [WebMethod] attribute :
[WebMethod]
public static Dictionary<int, string> ReadFile()
{
Dictionary<int, string> datalist = new Dictionary<int, string>();
var lines = File.ReadAllLines(#"C:\\temp\\Sample.txt");
int i = 1;
foreach (var line in lines)
{
datalist.Add(i, line);
i++;
}
return datalist;
}
Related issue:
How to get data from C# WebMethod as Dictionary<> and display response using jquery ajax?

Related

How to pass local storage item to MVC controller

I am trying to pass an array of strings from my local storage (key value) to MVC controller. Here's my code:
In cshtml View file:
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.Result);
}
}});
}
</script>
<button onClick="getFavouriteBooks()">Display Favourites</button>
My controller:
public async Task < ViewResult > Favourites(string ids) {
// code that fetches book data from API
if (data != null)
{
var bookList = JsonConvert.DeserializeObject < Book[] > (data);
foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
}
return View("Index");
}
The controller action gets called successfully on the button click but the ids parameter is always null even though it isn't when in the console. Where am I going wrong?
from what you have described, I strongly feel this is the problem of expecting asynchronous function to behave synchronously,
await foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
Try adding await before you call foreach loop. or better use for in loop
Thanks for your help everyone, the solution was actually to change this part of the ajax call to:
data: { ids: localStorage.getItem('videoIds') },
This code was tested in Visual Studio.
You have to create a viewModel:
public class IdsViewModel
{
public string[] Ids { get; set; }
}
Replace this:
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
// or you can use
var ids = localStorage.getItem('videoIds'); //it still will be working
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
with this
var ids= JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '/Home/Favourites',
data: { ids:ids },
success: function (result) {
....
and the action
public async Task <ActionResult> Favourites(IdsViewModel viewModel) {
var ids=viewModel.Ids;
.....

Pass array from client side to service side c#

I am calling a javascript function on button click using onclientclick with below function.
function addValues() {
debugger;
var arrValue = [];
var hdnValue = document.getElementById("hdn").value;
var strValue = hdnValue.split(',');
for (var i = 0; i < strValue.length; i++) {
var ddlValue = document.getElementById(strValue[i]).value;
arrValue.push(ddlValue);
}
}
arrValue array will have all the required values and how can I move this array values to server side for further process.
Update 1:
HTML:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
}
$.ajax({
url: '',
data: { ddlArray: arrddlValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
},
error: function (x, e) {
}
});
Code:
protected void btnSort_Click(object sender, EventArgs e)
{
try
{
if (Request["ddlArray[]"] != null)
{
string[] arrValues = Array.ConvertAll(Request["ddlArray[]"].ToString().Split(','), s => (s));
}
}
}
If your framework is ASP.Net you can pass it by $.ajax, I am passing array like:
$.ajax({
url: '',
data: { AbArray: arrValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
and get it in Back-end like:
if (request["AbArray[]"] != null)
{
int[] arrValues = Array.ConvertAll(request["AbArray[]"].ToString().Split(','), s => int.Parse(s));
}
suppose array is int.
the above sample is using Generic-Handler.
if you want to use webmethod do something like:
[WebMethod(EnableSession = true)]
public static void PassArray(List<int> arr)
{
}
and Ajax would be like:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
var jsonVal = JSON.stringify({ arr: arrValue });
$.ajax({
url: 'YourPage.aspx/PassArray',
data: jsonVal,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
}
Change Ajax Url as your PassArray address which mean YourPage.aspx should be change to page name which have PassArray in it's code-behind.
For more info Read This.
If you are using Asp.net WebForm Application,
Approach 1 : you can store your array value in a hidden input control and retrieve the saved data in your c# coding.
Approach 2 : define web method in your server side c# code and pass this javascript array value as ajax call.
link for Approach 1 : https://www.aspsnippets.com/Articles/Pass-JavaScript-variable-value-to-Server-Side-Code-Behind-in-ASPNet-using-C-and-VBNet.aspx
link for Approach 2 : https://www.aspsnippets.com/Articles/Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX.aspx
I would "stringify" the array by imploding it with a special char unlikely to appear in my values (for example: §), and then with the help of jQuery.ajax() function, I will send it to the backend (ASP.NET MVC) action method:
$.ajax({
url : 'http://a-domain.com/MyController/MyAction',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
My backend would be something like this (in MyController class):
[HttpPost]
public ActionResult MyAction(string data)
{
string[] arrValue = data.Split('§');
...
}
UPDATE
For ASP.NET forms, the ajax request would be:
$.ajax({
url : 'http://a-domain.com/MyPage.aspx/MyMethod',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
And the backend would be something like this:
[System.Web.Services.WebMethod]
public static void MyMethod(string data)
{
string[] arrValue = data.Split('§');
...
}
You will find a more precise explanation here: https://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

JSON Object always return undefined with AJAX

The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept

Why doesn't my ajax call reach my .NET WebMethod?

I can't for the life of me understand why this code isn't working. I need a second set of eyes to review it - TIA:
This function returns success, but the C# method is not called.
JavaScript
$(function() {
($("#survey").on("submit", function() {
var data = serializeForm();
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert('ok');
},
error: function(data) {
alert('failed');
}
}); //ajax
return false;
}));
function serializeForm() {
var data = new Object;
$("#survey input[type='checkbox']").each(
function(index) {
data[$(this).get(0).id] = $(this).get(0).checked ? 1 : 0;
});
data.otherEnviron = $("#survey input[type='text']").val();
var strData = JSON.stringify(data);
return strData;
}
});
Revised:
$(function () {
($("#survey").on("submit", function() {
var data = serializeForm();
alert(data);
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('ok-'+ data);
},
error: function (xml, textStatus, errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
}); //ajax
return false;
}));
Note:
strData="{\"ms\":1,\"google\":0,\"PHP\":0,\"otherEnviron\":\".NET\"}"
C# WebMethod
[WebMethod]
private void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
using (SqlConnection scon = new SqlConnection(connectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
}
}
Revised C#
[WebMethod]
public static void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
try
{
using (SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["C287577_NorthwindConnectionString"].ConnectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
scmd.Dispose();
}
} catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
This is still not working. No error msg is shown, only ok.
because WebMethod must be public and static
Similar question: ASP.NET jQuery error: Unknown Web Method
If you need more security around your ajax call, try moving it to a web service.
public static void SaveSurveyInfo
The method should be static and public in aspx pages to be hit.
In asmx it can be just public.

My jquery ajax call is not working when I call web services which retrieves data from database

I am new working with jquery ajax calls in fact my first time and, I am running into a issue here my web service is working but for some reason when I try to call it from jquery ajax the data is not retrieve.
Please I've been working the whole day on this and I need to finish it tonight.
My web method is this :
public Didyoumean SayHello(string search)
{
Didyoumean Didyoumean = new Didyoumean();
string cs = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand ("USP_DidYouMean",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#search",search);
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Didyoumean.SearchInput = reader["detail"].ToString();
}
reader.Close();
con.Close();
}
return Didyoumean;
}
my Didyoumean class is this:
public class Didyoumean
{
public string SearchInput { get; set; }
}
my ajax call is this (the error is most likely to be here)
function bla() {
var SearchInput = document.getElementById("#locationSearchInput").value;
var DataObject = { search: SearchInput };
$.ajax({
type: "POST",
url: "/kiosk/EmailCoupon.asmx/SayHello",
data: JSON.stringify({dataObject}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.tags_select a').html(data.d);
},
error: function () {
$('.tags_select a').html("<p>no suggestion</p>")
}
});
}
and finally my html
<input id="Button1" type="button" value="button" onclick="bla()"/>
<div class="tags_select">
Basically what I am trying to do is depending on the data in my database the application give suggestions for spelling errors.
note: do not pay attention to the name of the functions and methods this is just a test.
Your service might be like this
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Didyoumean SayHello(string search)
{
Didyoumean didyoumean = new Didyoumean();
didyoumean.searchInput = "result of " + search;
return didyoumean;
}
}
and your javascript is
function test() {
var SearchInput = "test";
$.ajax({
type: "POST",
url: "/WebService1.asmx/SayHello",
data: JSON.stringify({search:SearchInput}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var didYouMean = data.d;
alert(didYouMean.searchInput);
},
error: function (e) {
console.log(e);
}
});
}

Categories