Retrieve JSON Array from jQuery Ajax call in asp.net webpages - c#

I am trying to send some data through an ajax call of jQuery. My question is : how do I get hold of this JSON array in my Insert.cshtml file? I have tried Request["rows"], Request[0][rows], etc. but without any success.
Here, the data I am trying to send is this (multiple rows of form data):
[
{
"sl": "1",
"tname": "Gardening",
"ttype": "4",
"tduration": "12"
},
{
"sl": "2",
"tname": "Nursing",
"ttype": "4",
"tduration": "45"
}
]
jQuery Code:
$.ajax({
type: "POST",
url: "/Insert",
data: rows,
contentType: "application/json",
success: function (data, status) {
alert(status);
},
error: function (xhr, textStatus, error) {
var errorMessage = error || xhr.statusText;
alert(errorMessage);
}
});
Update: A partial demo in jsfiddle - http://jsfiddle.net/rafi867/gprQs/8/

I have tried to simulate your problem creating in App_Code a Sample.cs class:
public class Sample
{
public string sl { get; set; }
public string tname { get; set; }
public string ttype { get; set; }
public string tduration { get; set; }
}
Now your Insert.cshtml file should look like this:
#{
var sample = new Sample[]{
new Sample{ sl = "1", tname = "Gardening", ttype = "4", tduration = "12" },
new Sample{ sl = "2", tname = "Nursing", ttype = "4", tduration = "45" }
};
Json.Write(sample, Response.Output);
}
and the file (ReadSample.cshtml?) that holds your Sample objects should be:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="~/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.getJSON('/Insert', function (sample)
{
var custList = "";
$.each(sample, function (index, obj) {
custList += "<li>" + obj.sl + " - " + obj.tname +
" - " + obj.ttype + " - " + obj.tduration + "</li>";
})
$("#list").html("<ul>" + custList + "</ul>")
})
</script>
</head>
<body>
<div id="list"></div>
</body>
</html>
In my example I have readed the objects array with
$.getJSON('/Insert', function (sample)
and created an unordered list to display its content
$.each(sample, function (index, obj) {
custList += "<li>" + obj.sl + " - " + obj.tname +
" - " + obj.ttype + " - " + obj.tduration + "</li>";
})
$("#list").html("<ul>" + custList + "</ul>")
I hope this could help.

I have put a sample code for show how to display array items on web page by using jquery and css. By using this try to understand the concept and then apply it to your scenario.
HTML
<div class="dialog" id="unpaid-dialog" data-width="550" data-title="Checkout">
<ul>
<li id="serviceAndRetailDetails" style="text-align: left;"></li>
</ul>
</div>
Jquery
<script type="text/javascript">
var toBePaidItems = new Array();//create a array
var make = "";
$.ajax({
type: "GET",
url: "/Portal/GetServiceAndRetailSalesDetails",
dataType: 'json',
contentType: "application/json; charset=UTF-8",
data: { invoiceOrSaleId: invoiceOrSaleId, providerKey: providerKey },
success: function (response) {
make = "<table id='tblPayment'>";
toBePaidItems = [];
$.each(response, function (index, sr) {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td><td></tr>";
//insert into array
toBePaidItems.push(sr.AllocationOrInvoiceOrSaleId);
});
make += "</table>";
$("#serviceAndRetailDetails").html(make);
}
});
</script>
Controller Action Method
[HttpGet]
public JsonResult GetServiceAndRetailSalesDetails(Guid invoiceOrSaleId, string providerKey)
{
var items = new List<CheckOutServiceAndRetailItem>();
var serviceDetails = Repository.GetAllPayableItems(invoiceOrSaleId).ToList();
foreach (var s in serviceDetails)
{
var item = new CheckOutServiceAndRetailItem
{
AllocationOrInvoiceOrSaleId = s.Allocation.AllocationId,
Name = s.Allocation.Service.Name,
Price = s.LatestTotal,
Class = s.Allocation.Service.IsAnExtra,
};
items.Add(item);
}
return Json(items, JsonRequestBehavior.AllowGet);
}
Array Out Put
How to manipulate Arrays Here
Hope This will help to you.

The data parameter is meant to map name-value pairs to query string parameters as you can tell by the docs:
data
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
If you then go on to read the docs for the .param() method, this should help you understand what's going on with your request and how jQuery sends your object to the server.
You may just have to name your objects/arrays in your data object so you can refer to them in the Request.Forms object.

Related

Loading data into html table using ajax and SQL stored procedure

I have a stored procedure that selects all the fields in the table based on the date. I then created a method shown below to return the results as JSON.
[HttpGet]
public JsonResult GetResult()
{
MonthNameConverter converter = new MonthNameConverter();
string fullDate = converter.startOfMonth().ToShortDateString();
string[] split = fullDate.Split('/');
string date = "";
if(Convert.ToInt32(split[0]) < 10)
{
date = split[2] + "-0" + split[0];
}
else
{
date = split[2] + "-" + split[0];
}
var results = travelSOCC.GetLansingMileage(date).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
However when I go to append the data to an HTML table I'm getting an unidentified result.
$(function LoadData() {
$("#LansingTable tbody tr").remove();
$.ajax({
type: 'GET',
url: '#Url.Action("GetResult")',
dataType: 'json',
data: JSON,
success: function (data) {
$.each(data, function (item) {
var rows = "<tr><td>" + item.TravelDate + "</td><td>" + item.TripType + "</td></tr>";
$("#LansingTable tbody").append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.resonseText);
alert("Message: " + r.Message);
}
})
});
Any help is greatly appreciated.
Please modify $.each(data, function(item) { as below:
$.each(data, function(idx, item) {
Please refer documentation here for more information.

Ajax function not showing JSON List of Dates (Mvc5)

In my MVC5 View, I´am calling a JSON function.
The JSON function returns a AvaliableDates model, wich have a Userld(string) and a LIST of DateTime objects defined.
My view is only able to read Userld but DateTime-objects appears as "undefined"
Can anyone see why I am not getting JSON DateTime LIST values in my view?
My JSON function:
public JsonResult GetFreeAppointmentDays()
{
List<DateTime> avaliableBookingDays = new List<DateTime>();
DateTime x1 = new DateTime(2017, 04, 11, 0, 0, 0);
DateTime x2 = new DateTime(2017, 04, 12, 0, 0, 0);
avaliableBookingDays.Add(x1.Date);
avaliableBookingDays.Add(x2.Date);
useravaliableDates AvaliableDates = new useravaliableDates()
{
UserIDs = "4,5,2,0,0,0,2",
Avdata = avaliableBookingDays
};
return Json(AvaliableDates, JsonRequestBehavior.AllowGet);
}
Here is my View, with AJAX call:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
<div id="divshow"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Home/GetFreeAppointmentDays",
dataType: "json",
success: function (data) {
$('#divshow').append(data);
var items = '';
$.each(data.Avdata, function (i, item) {
var row = "UserIDs are: " + data.UserIDs + " Date " + i + " -> " + item[i].Date + "<br/>"
$('#divshow').append(row);
});
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
STRANGE: My JSON function return this
{"UserIDs":"4,5,2,0,0,0,2","Avdata":["\/Date(1491861600000)\/","\/Date(1491948000000)\/","\/Date(1492034400000)\/","\/Date(1492207200000)\/","\/Date(1492466400000)\/"]}
You are getting date in milliseconds format.
Convert the C# date object to a string format and change Avdata property to a List<String>
avaliableBookingDays.Add(x1.ToString("yyyy-MM-ddTHH:mm:ss"));
avaliableBookingDays.Add(x2.ToString("yyyy-MM-ddTHH:mm:ss"));
Then convert it to a javascript date object:
var row = "UserIDs are: " + data.UserIDs + " Date " + i + " -> " + new Date(item); + "<br/>"
You need a function which convert one date like \/Date(1491861600000)\/ to real one. For this you can use replace method.
function parseDate(value){
var newDate=new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
return newDate.getDate()+'/'(newDate.getMonth()+1)+'/'+newDate.getFullYear()
}
In your each method use parseDate function which I create above:
$.each(data.Avdata, function (i, item) {
var row = "UserIDs are: " + data.UserIDs + " Date " + i + " -> " + parseDate(item)+ "<br/>"
$('#divshow').append(row);
});

How to redirect data to a particular page using url in c#?

I am working on jQuery fileupload now here I am saving images once saved some data I need to post to my page
Here I have two applications (two separate applications) html.page to I am posting images to mvc upload controller and I had saved the image success fully
Now to get the respose data I need to redirect through url so I am redirecting through like this
public void ReturnResult(string jsonObj)
{
var hostName = " http://localhost:8988/cors/postmessage.html?MyURL=";
var s = jsonObj;
var filterUrl = hostName + s;
HttpContext.Current.Response.Redirect(filterUrl);
}
Once redirection to this page how could I get those data?
And I don't have any idea is this redirecting the data or not how could could I know that
data is redirecting or not could u plz help me get the data
this is my
redirected to this page
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery File Upload Plugin postMessage API</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>
'use strict';
var origin = /^http:\/\/example.org/,
//var origin = 'http://localhost:4071/Upload/UploadHandler.ashx',
target = new RegExp('^(http(s)?:)?\\/\\/' + location.host + '\\/');
alert(1);
alert(origin);
$(window).on('message', function (e) {
e = e.originalEvent;
var s = e.data,
xhr = $.ajaxSettings.xhr(),
f;
if (!origin.test(e.origin)) {
throw new Error('Origin "' + e.origin + '" does not match ' + origin);
}
if (!target.test(e.data.url)) {
throw new Error('Target "' + e.data.url + '" does not match ' + target);
}
$(xhr.upload).on('progress', function (ev) {
ev = ev.originalEvent;
e.source.postMessage({
id: s.id,
type: ev.type,
timeStamp: ev.timeStamp,
lengthComputable: ev.lengthComputable,
loaded: ev.loaded,
total: ev.total
}, e.origin);
});
s.xhr = function () {
return xhr;
};
if (!(s.data instanceof Blob)) {
f = new FormData();
$.each(s.data, function (i, v) {
f.append(v.name, v.value);
});
s.data = f;
}
$.ajax(s).always(function (result, statusText, jqXHR) {
if (!jqXHR.done) {
jqXHR = result;
result = null;
}
e.source.postMessage({
id: s.id,
status: jqXHR.status,
statusText: statusText,
result: result,
headers: jqXHR.getAllResponseHeaders()
}, e.origin);
});
});
</script>
</body>
</html>
Any help will greately appreciated thanks in advance
If you need to get data from the query string returned from the controller in your HTML page then you can use this function.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
you can get you values on page load like:
var MyURL= getUrlVars()['MyURL'];

jQuery AutoComplete multiple Output

I am using jQuery AutoComplete to fetch results from a DataBase based on the value inputted. The user will then click a search button to tell the page to search for that specific entries details.
I want to get 2 values, the Name and Title. I only want to display the Name to the user, while the page uses the Title as a search criteria.
eg: When a person types in Vehicle, the result will display Vehicle1, Vehicle2 in a list.
When the user clicks on Vehicle1, a hidden box will be issues with the Title, which would be Bike, and such as with Vehicle2, which will issue the hidden box with Car.
I can get the Name to show in the text box properly, but I cannot for the life of me (And after 2 days of searching) bind the Title to a hidden box.
JavaScript:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
//value: item.Title,
label: item.Name
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
ASPX Code:
<div class="ui-widget" >
<asp:TextBox ID="tbAuto" class="tb" runat="server">
</asp:TextBox>
<asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>
CodeBehind:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
var emp = new Employee();
var fetchEmail = emp.GetEmployeeList(prefix)
.Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
return fetchEmail.ToList();
}
}
CompletionClass: (Excuse the naming)
public class Employee
{
public string Title { get; set; }
public string Name { get; set; }
public string value { get; set; }
public List<Employee> GetEmployeeList(string prefixText)
{
List<Employee> cmpList = new List<Employee>();
SqlConnection db = DataConn.SqlConnection();
db.Open();
SqlTransaction transaction = db.BeginTransaction();
//var array = new ArrayList();
try
{
SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
}
}
command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
}
}
transaction.Commit();
}
catch (SqlException)
{
transaction.Rollback();
cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
//array.Add("Problem Getting Results.");
}
if (cmpList.Count == 0)
cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
//array.Add("Nothing to Display.");
//return array;
return cmpList;
}
}
Those modifications to your JavaScript should do the trick:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[name$="tbAuto"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/FetchEmailList",
data: "{ 'prefix': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
focus: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
return false;
},
select: function(event, ui) {
$('input[name$="tbAuto"]').val(ui.item.Name);
$('input[name$="tbHidden"]').val(ui.item.Title);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
};
});
</script>
The assumption here is that the selectors returns exactly the element which we are working on, if not they need to be adjusted.
Cool. I've been googling for this solution for days... excellent clean code!
Just a small remark: using jqueryUI 1.10, this
throws javascript exception.
.data('autocomplete')._renderItem = function(ul, item) {...
I've used
.data('ui-autocomplete')._renderItem = function(ul, item) {...
and everything works great.

Retaining drag position does not work: jQuery draggable: position()

I have the following code which will store coordinate positions of the div whenever it is moved. The positions are stored into database so that when user returns, it remains there. The following code works somewhat similar to that. But the positions are not accurately maintained when I do two – three movements.
Note: I think the problem is following lines of code
//var absolutePositionLeft = (ui.originalPosition.left) + (ui.offset.left);
//var absolutePositionTop = (ui.originalPosition.top) + (ui.offset.top);
var stopPositions = $(this).position();
var absolutePositionLeft = stopPositions.left;
var absolutePositionTop = stopPositions.top;
Note: I am getting the error "Microsoft JScript runtime error: 'absolutePosition.left' is null or not an object" when I use var absolutePositionLeft = ui.absolutePosition.left;
Can you please suggest how to overcome this?
The code:
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("#<%=dImage.ClientID%>").draggable(
{
drag: function (event, ui) {
//when dragging
$("#<%=dImage.ClientID%>").css("opacity", "0.3");
},
stop: function (event, ui) {
//when stopped
//showAlert();
debugger;
//var absolutePositionLeft = (ui.originalPosition.left) + (ui.offset.left);
//var absolutePositionTop = (ui.originalPosition.top) + (ui.offset.top);
var stopPositions = $(this).position();
var absolutePositionLeft = stopPositions.left;
var absolutePositionTop = stopPositions.top;
var elementName = ui.helper.attr('id');
saveCoords(absolutePositionLeft, absolutePositionTop, elementName);
$("#<%=dImage.ClientID%>").css("opacity", "1.0");
},
cursor: "move"
});
});
function showAlert()
{
alert("hai");
}
function saveCoords(x, y, el, id)
{
$.ajax({
type: "POST",
url: "GridViewHighlightTEST.aspx/SaveCoords",
data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
if (response.d != '1')
{
alert('Not Saved!');
}
},
error: function (response)
{
alert(response.responseText);
}
});
}
</script>
And the C# Code is
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = GetSavedCoords(1);
foreach (DataRow row in dt.Rows)
{
string elementName = row["element"].ToString();
System.Web.UI.HtmlControls.HtmlControl theControlElement = (HtmlControl)this.FindControl(elementName);
if (theControlElement != null)
{
theControlElement.Style.Add("left", row["xPos"].ToString() + "px");
theControlElement.Style.Add("top", row["yPos"].ToString() + "px");
}
}
}
I believe your problem is that
var stopPositions = $(this).position();
should be
var stopPositions = $(event.target).position();
In any case, it's extremely useful to use a JavaScript debugger, it will keep you sane. If you are using Chrome or IE use F12 to get to developer tools. If you're using Firefox get Firebug.
Using one of these tools can help you quickly verify what this actually is which, depending on the frameworks your using, can quickly get confusing. A debugger can also help you verify your DOM and code flow.

Categories

Resources