如何在Asp.Net服务器端使用JavaScript对象
本文关键字:JavaScript 对象 服务器端 Net Asp | 更新日期: 2023-09-27 18:13:53
嗨,我必须通过在asp.net中从客户端到服务器端调用方法在服务器端传递javascript对象。
我这样做。我在方法中传递javascript对象。现在我想在服务器端代码中使用这个对象,但是我不能这样做。
我一直这样做到现在,如果我做错了什么,请告诉我。
aspx code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
// var JsonNewOne = {
// returnHeader: { "ID": -1, "OrderHeaderID": 5, "StatusID": 1, "DeliveryCharge": 0, "CreatedBy": "77777777", "ApprovedBy": "77777777" }
// };
var JsonNewOne = { "forename": "Phil", "surname": "Curnow", "age": 41 };
var jsonobj = eval(JsonNewOne);
var abc = JSON.stringify(jsonobj);
function GetServerDate(format) {
$.ajax({
type: "post",
url: "JSONTest.aspx/GetServerDate",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"format":"' + format + '"}',
success: function (result) {
OnSuccess(result.d);
},
error: function (xhr, status, error) {
OnFailure(error);
}
});
}
function OnSuccess(dateTime) {
if (dateTime) {
document.getElementById("currentDate").innerHTML = dateTime;
}
}
function OnFailure(error) {
alert(error);
}
</script>
</head>
<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<div>
<input type="button" value="Show UTC Server Time" onclick="GetServerDate(JsonNewOne)" />
<input type="button" value="Show Local Server Time" onclick="GetServerDate(JsonNewOne)" />
<label id="currentDate">
This is current Date Time in Web Server</label>
</div>
</form>
</body>
</html>
服务器端代码:
[System.Web.Services.WebMethod]
public static string GetServerDate( string format)
{
try
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(format));
Person obj = (Person)ser.ReadObject(stream);
}
catch (Exception ex)
{
return null;
}
}
Person.cs文件:
public class Person
{
public string forename { get; set; }
public string surname { get; set; }
public int age { get; set; }
}
var JsonNewOne = { "forename": "Phil", "surname": "Curnow", "age": 41 };
var jsonobj = eval(JsonNewOne);
var abc = JSON.stringify(jsonobj);
function GetServerDate(abc) {
$.ajax({
type: "post",
url: "JSONTest.aspx/GetServerDate",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"format":"' + abc + '"}',
success: function (result) {
OnSuccess(result.d);
},
error: function (xhr, status, error) {
OnFailure(error);
}
});
}
function OnSuccess(dateTime) {
if (dateTime) {
document.getElementById("currentDate").innerHTML = dateTime;
}
}
function OnFailure(error) {
alert(error);
}
</script>