Passing objects to ASP :NET Webservice through JSON - asp.net

Im trying to send a custom HTML object from my ASP 2.0 website to my webservice through jQuery ajax. But I cant get it to work.
Everything is parsed correct in my webservice when I drop the ObjectHTML part. But I get an error when I add the ObjectHTML part.
Is it possible to send custom javascript objects?
function SavePage() {
var rowCount = $('#pageArea div.object').length;
var i = 1;
var objects = "[";
$('.object').each(function(index) {
var objectHtml = new ObjectHTML($(this).html());
objects += "{'ObjectID': " + "'" + $(this).attr('objectid') + "', 'ObjectIndex': '" + $(this).attr('objectindex') + "', 'ObjectHTML': " + objectHtml + "}";
if (i == rowCount)
objects += ""
else
objects += ",";
i++;
});
objects += "]";
alert("{'objects': " + objects + "}");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Folder/ObjectService.asmx/SavePage",
data: "{'objects': " + objects + "}",
dataType: "json",
success:
function(msg) {
alert("Success!");
},
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error Occured: " + errorThrown);
}
});
}
function ObjectHTML(rawHtml) {
this.Html = rawHtml;
}
Webservice code:
[WebMethod(EnableSession = true)]
public string SavePage(List<PageObject> objects)
{
return "";
}
public class PageObject
{
private string _objectid, _objectindex;
private ObjectHTML _objectHtml;
public string ObjectID
{
get { return _objectid; }
set { _objectid = value; }
}
public string ObjectIndex
{
get { return _objectindex; }
set { _objectindex = value; }
}
public ObjectHTML ObjectHTML
{
get { return _objectHtml; }
set { _objectHtml = value; }
}
}
public class ObjectHTML
{
private string _Html;
public string Html
{
get { return _Html; }
set { _Html = value; }
}
}

It looks to me like you are getting a little confused between your C# classes on your server and the Javascript classes in your script.
One thing that you could do is encode your html for JSOn by using JSON.Stringify
var myObject = JSON.stringify({
ObjectId: $(this).attr('objectid'),
ObjectIndex: $(this).attr('objectIndex'),
ObjectHtml: $(this).html()
});
This will make sure that the html is encoded as valid JSON

Related

my action method returning {"success=true,message="work done"} ASP.net MVC 5

Here is my create action method. I want get alert form it when success is true.
public JsonResult Create(Student student ,HttpPostedFileBase img)
{
if (ModelState.IsValid)
{
if (img !=null)
{
var name = Path.GetFileNameWithoutExtension(img.FileName);
var ext = Path.GetExtension(img.FileName);
var filename = name + DateTime.Now.ToString("ddmmyyyff") + ext;
img.SaveAs(Server.MapPath("~/img/"+filename));
student.ImageName = filename;
student.Path = "~/img/" + filename;
}
db.Students.Add(student);
db.SaveChanges();
return Json(new { success = true, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
ViewBag.ClassID = new SelectList(db.Classes, "Id", "Name", student.ClassID);
return new JsonResult { Data = new { success = false, message = "data not saved" } };
}
Here is my ajax function :
function onsub(form) {
$.validations.unobtrusive.parse(form);
if (form.valid()) {
var ajaxConfig = {
type: "POST",
url: form.action,
data: new FormData(form),
success: function (response) {
if (response.success ) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}
}
if ($(form).attr("enctype") == "multipart/form-data") {
ajaxConfig["contentType"] = false;
ajaxConfig["processData"] = false;
}
$.ajax(ajaxConfig);
}
return false;
}
How can I get an alert form it
without reloading the form. I also want to submit images and other files to create an action method.
This is the result that I get after submitting the form:
In your case you are calling Create action which returning the JSON Result and the same Json response is displayed in browser.
Their should be a View page from where you will call this method by using the Ajax call, then you will be able to see your alert message.

HTML DOM not working with JavaScript page

Getting HTML DOM from websites that work with client-side (JavaScript)
It doesn't work because
<div class="currTableContainer" id="divCurrTableContainer">
is empty. There is nothing in it. You wont find a table in it. Hence the nullpointer. The HTML you're looking for is generated by a script(ajax).
Check the loaded HTML to confirm.
Because I was bored I decided to finish your homework. You can't use HAP in this case. You have to use the ajax service they provided. Also better since the data is prone to change a lot. The code that is used on the site(ajax script) looks like this:
$("document").ready(function () {
$.ajax({
type: "POST",
url: '/_layouts/15/LINKDev.CIB.CurrenciesFunds/FundsCurrencies.aspx/GetCurrencies',
async: true,
data: "{'lang':'" + document.getElementById("ctl00_ctl48_g_5d7fc52f_a66d_4aa2_8d6c_c01fb4b38cb2_hdnLang").value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != null && msg.d.length > 0) {
var contentHTML = "<table class='currTable' cellspacing='0' rules='all' style='border-width:0px;border-collapse:collapse;'>"
+ "<tbody><tr class='currHeaderRow'>"
+ "<th scope='col'>" + document.getElementById("ctl00_ctl48_g_5d7fc52f_a66d_4aa2_8d6c_c01fb4b38cb2_hdnCurrency").value + "</th><th scope='col'>" + document.getElementById("ctl00_ctl48_g_5d7fc52f_a66d_4aa2_8d6c_c01fb4b38cb2_hdnBuy").value + "</th><th scope='col'>" + document.getElementById("ctl00_ctl48_g_5d7fc52f_a66d_4aa2_8d6c_c01fb4b38cb2_hdnSell").value + "</th>"
+ "</tr>";
for (var i = 0; i < msg.d.length; i++) {
if (msg.d[i].CurrencyID.length > 0) {
contentHTML += "<tr class='currRow'>"
+ "<td>" + msg.d[i].CurrencyID + "</td><td>" + msg.d[i].BuyRate + "</td><td class='lastCell'>" + msg.d[i].SellRate + "</td>"
+ "</tr>";
}
}
contentHTML += "</tbody></table>";
$("#divCurrTableContainer").html(contentHTML);
if ($(".bannerElements").length > 0)
FixCurrenciesRatesScroll();
}
},
error: function (msg) {
}
});
});
As you can see the script uses an URL from a different part of the site to update their currency. In order to fetch it you just make http request with the following JSON {"lang":"en"}. I have translated the script into it's equivalent in C# below. The response from the http request will be JSON formatted. Which means you will have to create a class that can be used to serialize the data. I recommend you look at Newtonsoft for this since I can't do all your homework.
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace test
{
class Program
{
public static void Main(string[] args)
{
try
{
string webAddr = "http://www.cibeg.com/_layouts/15/LINKDev.CIB.CurrenciesFunds/FundsCurrencies.aspx/GetCurrencies";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Expect = "application/json";
string datastring = "{\"lang\":\"en\"}";
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(datastring);
httpWebRequest.ContentLength = data.Length;
httpWebRequest.GetRequestStream().Write(data, 0, data.Length);
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
//Now you have your response.
//or false depending on information in the response
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}

how do I parse the http response object coming from asmx

$scope.Edit = function (id) {
console.log("edit id : " + id);
$scope.Employee = {};
$scope.eid = id;
var data = JSON.stringify({empid: $scope.eid});
var url = "/services/EmployeeService.asmx/EditEmployee";
$http.post(url, data).then(function (response) {
$scope.Employee = response.data;
console.log($scope.Employee.fname);
console.log($scope.Employee);
var mydata = jQuery.parseJSON(JSON.stringify(response.data));
console.log(mydata);
}, function (response) {
console.log(response.status);
console.log(response.statusText);
});
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string EditEmployee(int empid)
{
Employee employee = new Employee();
if (emplist.Count > 0)
{
foreach (Employee emp in emplist)
{
if (emp.empId == empid)
{
employee.empId = empid;
employee.fname = emp.fname;
employee.city = emp.city;
employee.mobile = emp.mobile;
employee.country = emp.country;
break;
}
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
List<Employee> elist = new List<Employee>();
elist.Add(employee);
return new JavaScriptSerializer().Serialize(elist);
}
This is I got from the response
Object
d:"[{"empId":103,"fname":"sujith","city":"trichy","mobile":"56456456","country":"India"}]"
proto : Object
how do I parse angular js object. I want to access like this: $scop.Employee.empId,$scope.Employee.fname
Thanks & Regards
arun
Are you sure that the object you are receiving is starting and ending with " " (double quotes)
Change the following line
$scope.Employee = response.data;
with
$scope.Employee = response.data.d[0];
Try this. This should work :
$scope.Edit = function (id) { console.log("edit id : " + id); $scope.Employee = {}; $scope.eid = id; var data = JSON.stringify({empid: $scope.eid}); var url = "/services/EmployeeService.asmx/EditEmployee"; $http.post(url, data).then(function (response) {
$scope.Employee = response.data.d[0];
console.log($scope.Employee.fname);
console.log($scope.Employee); }, function (response) {
console.log(response.status);
console.log(response.statusText); });
}
$scope.Edit = function (id) {
console.log("edit id : " + id);
$scope.Employee = {};
$scope.eid = id;
var data = JSON.stringify({ empid: $scope.eid });
var url = "/services/EmployeeService.asmx/EditEmployee";
$http.post(url, data).then(function (response) {
$scope.Employee = JSON.parse( response.data.d);
console.log("empid: " + $scope.Employee.empId);
console.log("fname: " + $scope.Employee.fname);
console.log("city: " + $scope.Employee.city);
console.log("country: " + $scope.Employee.country);
}, function (response) {
console.log(response.status);
console.log(response.statusText);
});
}
enter code here
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string EditEmployee(int empid)
{
Employee employee = new Employee();
if (emplist.Count > 0)
{
foreach (Employee emp in emplist)
{
if (emp.empId == empid)
{
employee.empId = empid;
employee.fname = emp.fname;
employee.city = emp.city;
employee.mobile = emp.mobile;
employee.country = emp.country;
break;
}
}
}
return new JavaScriptSerializer().Serialize(employee);
}
enter code here
thank you Vikas Thakur, Abhijeet Jaiswal, it helped me to solved it, now it is working, what mistake is in asmx webservice webmethod I should return Employee object as string, previously I wrongly add it to the list and return the list. the webmethod return type is string so it is not parsing. now it is parsing. thank you both of you helped me.

selecting all the records from the database using jquery ajax in asp.net

i want to generate the table of contents from database.. using jquery ajax in asp.net, i am using sql server 2008 as a backend. for this i created a webmethod in my normal aspx page. and on the clientside wrote the ajax script to fetch records but when i loop through the results, i gets message undefined and nothing happens.. i want to generate table out of the records from database below is my webmethod.
[WebMethod]
public static Poll[] GetPollDetailed()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("sp_SelectQuestion", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#siteid", 3);
DataTable dt = new DataTable();
da.Fill(dt);
List<Poll> _poll1 = new List<Poll>();
foreach (DataRow row in dt.Rows)
{
Poll _poll = new Poll();
_poll.QuestionID = Convert.ToInt32(row["questionID"]);
_poll.Question = row["question"].ToString();
_poll.Published = Convert.ToInt32(row["visible"]);
_poll.Date = Convert.ToDateTime(row["Added_Date"]);
}
return _poll1.ToArray();
}
public class Poll
{
public Poll() { }
private int _questionId, _published;
private string _question;
private DateTime _date;
public int QuestionID
{
get { return _questionId; }
set { _questionId = value; }
}
public string Question
{
get { return _question; }
set { _question = value; }
}
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
public int Published
{
get { return _published; }
set { _published = value; }
}
}
</code>
and below is my script.
<code>
$(this).load(function () {
$.ajax({
type: "POST",
url: "AddPollAJax.aspx/GetPollDetailed",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
error: function (data) {
alert("Error: " + data.responseText);
}
});
});
</code>
can any one please help me to resolve this issue, i am very curious about it.
Assuming your service is configured correctly to return JSON data, issue lies at your js code fragment for success callback i.e.
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
MS ASP.NET script services always return a wrapped JSON due to security issues, so you need unwrap resultant JS object to get the actual data. So you need to change the code to
success: function (result) {
var data = result.d; // actual response will be in this property
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
BTW, ASP.NET Web Services are now considered legacy, so I will suggest you to migrate to WCF services instead.

Flex 3: Getting variables from URL

If I have an application located at http://sitename.com/myapp/ and i want to pass in a variable via the url (i.e. - http://sitename.com/myapp/?name=Joe), how can I get that name variable into a string var?
I use the class Adobe provided in this article.
package
{
import flash.external.*;
import flash.utils.*;
public class QueryString
{
private var _queryString:String;
private var _all:String;
private var _params:Object;
public function get queryString():String
{
return _queryString;
}
public function get url():String
{
return _all;
}
public function get parameters():Object
{
return _params;
}
public function QueryString()
{
readQueryString();
}
private function readQueryString():void
{
_params = {};
try
{
_all =
ExternalInterface.call("window.location.href.toString");
_queryString =
ExternalInterface.call("window.location.search.substring", 1);
if(_queryString)
{
var params:Array = _queryString.split('&');
var length:uint = params.length;
for (var i:uint=0,index:int=-1; i 0)
{
var key:String = kvPair.substring(0,index);
var value:String = kvPair.substring(index+1);
_params[key] = value;
}
}
}
}catch(e:Error) { trace("Some error occured.
ExternalInterface doesn't work in Standalone player."); }
}
}
}
UPDATE: An updated version of this class can also be found here, although I haven't tried this one.
UPDATE 2:
Here's an example on how to use the Querystring class:
public function CheckForIDInQuerystring():void
{
// sample URL: http://www.mysite.com/index.aspx?id=12345
var qs:QueryString = new QueryString;
if (qs.parameters.id != null)
{
// URL contains the "id" parameter
trace(qs.parameters.id);
}
else
{
// URL doesn't contain the "id" parameter
trace("No id found.");
}
}
Divide 'em with String.split() and conquer:
var url:String = "http://www.xxx.zzz/myapp?arg1=vae&arg2=victus";
var params:String = url.substr(url.lastIndexOf("?") + 1);
if (params.length == url.length) return; //no params
for each (var pair:String in params.split("&"))
{
trace("Got parameter:");
var nameValue:Array = pair.split("=");
trace("name: " + nameValue[0] + ", value: " + nameValue[1]);
}
Output:
Got parameter:
name: arg1, value: vae
Got parameter:
name: arg2, value: victus

Resources