如何使用 Json 发送数据并获得 asp.net 服务
How to send data using Json and get in asp.net services
我是 php 开发人员,最近转为 asp,我想将数据发送到 Web 服务并到达那里,但我无法提出解决方案。
在 php 中,如果您想为后端处理目的访问数据,我们只需使用
.Serialize(); 方法,
例如:
<form id="loginForm">
<input class="form-control" name="UserEmail" placeholder="Email" type="email" required=""/>
</form>
并且在 Jscript 函数中我们将序列化表单,例如:
var data = $("#loginForm").serialize();
并且在流程方面我可以通过输入名称来调用它,但是在 asp.net 中我不能这样做,我可能会遗漏一些东西或者 asp.net 不支持这种方法全部?不懂请各位程序员帮帮我
HTML+JS+ 网络服务
JS:
<script type="text/javascript">
function getProject() {
var data = "";
var strUser = "<%=nowUser%>";
$.ajax({
type: 'post',
url: '<%=AppRoot%>main/BackWebservice.asmx/LoadProjects',
async: true,
dataType: 'json',
data: { strAdmin: strUser },
success: function (result) {
var json = eval(result); //数组
var optionstring = "";
$.each(json, function (index, item) {
//循环获取数据
var name = json[index].Name;
var idnumber = json[index].ID;
optionstring += "<option value=\"" + idnumber + "\" >" + name + "</option>";
});
$("#userProject").html("<option value=\"" + 0 + "\"'>所有项目</option> " + optionstring);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
</script>
网络服务
[WebMethod]
public void LoadProjects(string strAdmin)
{
List<Project> mProjects = new List<Project>();
string stuJsonString = "";
bool bManager = false;
using (SqlConnection connection1 = new SqlConnection(Cfg.SqlServer))
{
connection1.Open();
string mstrsql1 = "SELECT * FROM ShuiUser where 账号='" + strAdmin + "'";
using (SqlCommand CMD1 = new SqlCommand(mstrsql1, connection1))
{
SqlDataReader DR1 = CMD1.ExecuteReader();
while (DR1.Read())
{
if (DR1["管理"].ToString() == "1")
{
bManager = true;
}
}
DR1.Close();
}
connection1.Close();
}
using (SqlConnection connection2 = new SqlConnection(Cfg.SqlServer))
{
connection2.Open();
string mstrsql2 = "";
if (bManager)
{
mstrsql2 = "select * from ShuiProject";
}
else
{
mstrsql2 = "select a.* from ShuiProject a,ShuiUser b where a.[编号]=b.[项目] AND b.[账号]='" + strAdmin + "' ";
}
using (SqlCommand CMD2 = new SqlCommand(mstrsql2, connection2))
{
SqlDataReader DR2 = CMD2.ExecuteReader();
while (DR2.Read())
{
Project mProject = new Project();
mProject.ID = Convert.ToInt16(DR2["编号"]);
mProject.Name = DR2["名称"].ToString();
mProjects.Add(mProject);
}
DR2.Close();
}
connection2.Close();
}
stuJsonString = JsonConvert.SerializeObject(mProjects);
//主要是下面的两句 The most important two sentences
Context.Response.Write(stuJsonString);
Context.Response.End();
}
ASPX:
<form runat=”server” id="loginForm">
<asp:Textbox runat=”server” cssClass="form-control" id="UserEmail" placeholder="Email" TextMode=”email” required=""/>
</form>
在代码隐藏 (.cs) 上:
using Newtonsoft.Json;
var obj=new {
Email= UserEmail.Text.Trim()
};
var j=JsonConvert.SerializeObject(obj);
我假设您正在处理网络表单。
你必须在 asp 中使用 jsonp
$.ajax({
url: 'you path',
数据类型:'jsonp',
数据: {....}
});
您应该使用 Id 属性 并使用 stingify() 方法而不是序列化。
HTML
<input class="form-control" Id="UserEmail" placeholder="Email" type="email" required=""/>
JS
function YesFunction() {
var email= $("#UserEmail").val();
var d= [];
d.push(email);
var jsndta = JSON.stringify({ d: d});
$.ajax({
type: "POST",
url: "wbservices/SearchSchoolInfoAndInventory.asmx/Searchschoolbesicinfo",
data: jsnDta,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var rtnData = r.d; //all returned data...
var respDta = [];
$.map(rtnData, function (item, index) {
var j = [
item.status,
item.msg,
];
respDta.push(j);
});
$.each(respDta, function (key, value) {
var status = value[0];
var msg = value[1];
if (status == true) {
table.html(msg);
} else {
}
}); //1st out loop ends here...
},
error: function (jqXHR, textStatus, errorThrown) {
// $("#responseMovDetails").html(jqXHR + textStatus + errorThrown);
alert("error while loading Purchases Head" + jqXHR + textStatus + errorThrown);
}
});
}
现在创建一个 class 并创建两个 public 变量,并通过在 Web 服务 class 中创建 class 对象来调用这两个变量 class。
public class RequestResponse
{
public bool status { get; set; }
public string msg { get; set; }
}
[WebMethod]
public List<RequestResponse>ActivatePBudget(List<string> d)
{
RequestResponse r = new RequestResponse();
List<RequestResponse> list = new List<RequestResponse>();
string Email= d[0].ToString();
//establish connection. I have established connection in separate class.
DbCon dbcon = new DbCon();
string constr = dbcon.dbconnection();
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string CheckEmail = "select * from Table_Name where Email= @m";
SqlCommand getcmd= new SqlCommand(CheckEmail,con);
getcmd.Parameters.AddWithValue("@m", Email);
SqlDataReader reader=getbhidcmd.ExecuteReader();
if(reader.Read())
{
r.status = true;
r.msg = "Valid User Or Redirect user to another page";
list.Add(r);
reader.Close();
}
else
{
reader.Close();
r.status = false;
r.msg = "Invalid Email";
list.Add(r);
}
}
catch (Exception ex)
{
r.status = false;
r.msg = "Invalid Email" + ex.ToString();
list.Add(r);
}
finally
{
con.Close();
}
return list;
}
我是 php 开发人员,最近转为 asp,我想将数据发送到 Web 服务并到达那里,但我无法提出解决方案。 在 php 中,如果您想为后端处理目的访问数据,我们只需使用 .Serialize(); 方法,
例如:
<form id="loginForm">
<input class="form-control" name="UserEmail" placeholder="Email" type="email" required=""/>
</form>
并且在 Jscript 函数中我们将序列化表单,例如:
var data = $("#loginForm").serialize();
并且在流程方面我可以通过输入名称来调用它,但是在 asp.net 中我不能这样做,我可能会遗漏一些东西或者 asp.net 不支持这种方法全部?不懂请各位程序员帮帮我
HTML+JS+ 网络服务 JS:
<script type="text/javascript">
function getProject() {
var data = "";
var strUser = "<%=nowUser%>";
$.ajax({
type: 'post',
url: '<%=AppRoot%>main/BackWebservice.asmx/LoadProjects',
async: true,
dataType: 'json',
data: { strAdmin: strUser },
success: function (result) {
var json = eval(result); //数组
var optionstring = "";
$.each(json, function (index, item) {
//循环获取数据
var name = json[index].Name;
var idnumber = json[index].ID;
optionstring += "<option value=\"" + idnumber + "\" >" + name + "</option>";
});
$("#userProject").html("<option value=\"" + 0 + "\"'>所有项目</option> " + optionstring);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
</script>
网络服务
[WebMethod]
public void LoadProjects(string strAdmin)
{
List<Project> mProjects = new List<Project>();
string stuJsonString = "";
bool bManager = false;
using (SqlConnection connection1 = new SqlConnection(Cfg.SqlServer))
{
connection1.Open();
string mstrsql1 = "SELECT * FROM ShuiUser where 账号='" + strAdmin + "'";
using (SqlCommand CMD1 = new SqlCommand(mstrsql1, connection1))
{
SqlDataReader DR1 = CMD1.ExecuteReader();
while (DR1.Read())
{
if (DR1["管理"].ToString() == "1")
{
bManager = true;
}
}
DR1.Close();
}
connection1.Close();
}
using (SqlConnection connection2 = new SqlConnection(Cfg.SqlServer))
{
connection2.Open();
string mstrsql2 = "";
if (bManager)
{
mstrsql2 = "select * from ShuiProject";
}
else
{
mstrsql2 = "select a.* from ShuiProject a,ShuiUser b where a.[编号]=b.[项目] AND b.[账号]='" + strAdmin + "' ";
}
using (SqlCommand CMD2 = new SqlCommand(mstrsql2, connection2))
{
SqlDataReader DR2 = CMD2.ExecuteReader();
while (DR2.Read())
{
Project mProject = new Project();
mProject.ID = Convert.ToInt16(DR2["编号"]);
mProject.Name = DR2["名称"].ToString();
mProjects.Add(mProject);
}
DR2.Close();
}
connection2.Close();
}
stuJsonString = JsonConvert.SerializeObject(mProjects);
//主要是下面的两句 The most important two sentences
Context.Response.Write(stuJsonString);
Context.Response.End();
}
ASPX:
<form runat=”server” id="loginForm">
<asp:Textbox runat=”server” cssClass="form-control" id="UserEmail" placeholder="Email" TextMode=”email” required=""/>
</form>
在代码隐藏 (.cs) 上:
using Newtonsoft.Json;
var obj=new {
Email= UserEmail.Text.Trim()
};
var j=JsonConvert.SerializeObject(obj);
我假设您正在处理网络表单。
你必须在 asp 中使用 jsonp $.ajax({ url: 'you path', 数据类型:'jsonp', 数据: {....} });
您应该使用 Id 属性 并使用 stingify() 方法而不是序列化。
HTML
<input class="form-control" Id="UserEmail" placeholder="Email" type="email" required=""/>
JS
function YesFunction() {
var email= $("#UserEmail").val();
var d= [];
d.push(email);
var jsndta = JSON.stringify({ d: d});
$.ajax({
type: "POST",
url: "wbservices/SearchSchoolInfoAndInventory.asmx/Searchschoolbesicinfo",
data: jsnDta,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var rtnData = r.d; //all returned data...
var respDta = [];
$.map(rtnData, function (item, index) {
var j = [
item.status,
item.msg,
];
respDta.push(j);
});
$.each(respDta, function (key, value) {
var status = value[0];
var msg = value[1];
if (status == true) {
table.html(msg);
} else {
}
}); //1st out loop ends here...
},
error: function (jqXHR, textStatus, errorThrown) {
// $("#responseMovDetails").html(jqXHR + textStatus + errorThrown);
alert("error while loading Purchases Head" + jqXHR + textStatus + errorThrown);
}
});
}
现在创建一个 class 并创建两个 public 变量,并通过在 Web 服务 class 中创建 class 对象来调用这两个变量 class。
public class RequestResponse
{
public bool status { get; set; }
public string msg { get; set; }
}
[WebMethod]
public List<RequestResponse>ActivatePBudget(List<string> d)
{
RequestResponse r = new RequestResponse();
List<RequestResponse> list = new List<RequestResponse>();
string Email= d[0].ToString();
//establish connection. I have established connection in separate class.
DbCon dbcon = new DbCon();
string constr = dbcon.dbconnection();
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string CheckEmail = "select * from Table_Name where Email= @m";
SqlCommand getcmd= new SqlCommand(CheckEmail,con);
getcmd.Parameters.AddWithValue("@m", Email);
SqlDataReader reader=getbhidcmd.ExecuteReader();
if(reader.Read())
{
r.status = true;
r.msg = "Valid User Or Redirect user to another page";
list.Add(r);
reader.Close();
}
else
{
reader.Close();
r.status = false;
r.msg = "Invalid Email";
list.Add(r);
}
}
catch (Exception ex)
{
r.status = false;
r.msg = "Invalid Email" + ex.ToString();
list.Add(r);
}
finally
{
con.Close();
}
return list;
}