I have implemented a web page with asp.net.
It has some ajax function.
in ajax function, Get a image path from server side webMethod.
The image path consist of root operator, for example "~/Images/Icons/SendEmail.png".
In Client side, I want to set image path to img element.
How can I set the image from this relative path?
Here is my code snippet.
Please refer this and give me some advices. Thank you in advance.
Clien side
function DrawImage() {
$.ajax({
type: 'POST',
url: '../Management/GetImage',
data: '{Index: "' + Index + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (resp) {
if (resp.d == null) {
return;
}
var ImagePath = resp.d;
var image = document.createElement('img');
image.src = ImagePath; // e.g. "~/Images/Image.png"
$(imageDiv).append(image);
},
error: function (msg) {
alert("Failed to Image: " + msg.statustext);
}
});
}
Server Side WebMethod
[WebMethod]
public static string GetImage(string Index)
{
string conStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(conStr);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Select_ImagePath";
command.Parameters.AddWithValue("#Index", Index);
string imgPath = "";
try
{
conn.Open();
SqlDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
imgPath = (string)dataReader["Image_Path"]; // e.g. "~/Images/Image.png"
}
}
catch (Exception err)
{
}
finally
{
conn.Close();
}
return imgPath;
}
I solved this problem by just implementing some function in javascript like below.
function ConvertRelPathToAbsPath(path)
{
var absPath ="";
if (path.length > 0)
absPath = window.location.protocol + '//' + location.host + path.substr(1);
return absPath;
}
Related
I'm kinda new to using AJAX call to a WebMethod. I feel my Web Method logic is but maybe someone could help out here. I do get an unknown web method error when I log the AJAX response to the console. Below is my Web method and AJAX call code.
$("#btnLogin").click(function () {
email = $("#txtEmailAddress").val();
password = $("#txtPassword").val();
//Create the login info object
var loginInfo = {};
//Set the object properties and value
loginInfo.Email = email;
loginInfo.Password = password;
//Make the ajax call
$.ajax({
type: "POST",
dataType: 'json',
url: '<%=ResolveUrl("identicate.aspx/ValidateUsersToken") %>',
data: '{loginInfo:' + JSON.stringify(loginInfo) + '}',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d == null || data.d == undefined)
{
alert("Username or password not correct = " + data.d);
console.log(data);
console.log(loginInfo);
console.log(this.url);
}
},
error: function (data) {
console.log(data);
console.log(loginInfo);
console.log(this.url);
alert(data.d);
}
});
});
And here's my web method
[WebMethod]
public static String ValidateUsersToken(iloginmodel loginInfo)
{
//Variable to hold the user email address
String email = string.Empty;
//Get the connection string from config file
String connectionString = iDbConfiguration.GetConnectionString();
//Create the command text
String commandText = "select Email, Password from VUser where Email = #Email & Password = #Password";
//Create database connection object and open it
using(SqlConnection loginConnection = new SqlConnection(connectionString))
{
//Set command paramters
SqlCommand loginCommand = new SqlCommand(commandText, loginConnection);
//Set command type to text
loginCommand.CommandType = System.Data.CommandType.Text;
//Add parameter to command
loginCommand.Parameters.AddWithValue("Email", loginInfo.Email);
loginCommand.Parameters.AddWithValue("#Password", loginInfo.Password);
//Open the database connection
try
{
loginConnection.Open();
SqlDataReader loginReader = loginCommand.ExecuteReader();
if(loginReader.HasRows)
{
HttpContext.Current.Response.Write(loginReader.ToString());
while (loginReader.Read())
{
if (loginReader.HasRows)
{
email = loginReader["Email"].ToString();
}
}
}
}
catch(SqlException sqlEx)
{
HttpContext.Current.Response.Write(sqlEx.Message);
}
finally
{
loginConnection.Close();
}
}
return email;
}
I am php developer and recently switched to asp, I want to send data to web services and get there but I am unable to come up with a solution.
In php if you want to access data for back-end process purpose we simply use
.Serialize(); method,
for example:
<form id="loginForm">
<input class="form-control" name="UserEmail" placeholder="Email" type="email" required=""/>
</form>
and in Jscript function we will serialize the form, e.g:
var data = $("#loginForm").serialize();
and in process side I can call it by inputs name, But in asp.net I am unable to do the same, I might be missing something or does asp.net do not support such approach at all? I do not know please programmers help me out.
You should use Id property and use stingify() method instead of serialization.
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);
}
});
}
Now create a class and create two public variables and call both variables by creating class object in web service 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;
}
HTML+JS+ WEB-SERVICE
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>
WEB-SERVICE
[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>
On Codebehind(.cs):
using Newtonsoft.Json;
var obj=new {
Email= UserEmail.Text.Trim()
};
var j=JsonConvert.SerializeObject(obj);
I have assumed that you are working on webforms.
you must used jsonp in asp
$.ajax({
url: 'you path',
datatype: 'jsonp',
data: {....}
});
this code working in aspx, but this code in not working in mvc project..
error: POST http://localhost:1208/AWD/Login.asmx/logi 500 (Internal Server Error)
var Email = $("#uwd").val();
var pwd = $("#pwd").val();
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/AWD/Login.asmx/logi",
data: "{'username':'" + Email + "','password':'" + pwd + "'}",
dataType: "json",
success: function (response) {
var obj = response.d;
alert(obj);
if (obj == "01") {
alert("login ok");
}
else {
alert("login no");
}
},
error: function (result) {
alert("Error");
}
});
[WebMethod]
public static string logi(string username,string password)
{
string result = null;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand ilogin = new SqlCommand("select *from login where email='" + username + "' and password='" + password + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(ilogin);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
result = "ok";
return result;
}
else
{
result ="no";
return result;
}
}
Seems its not valid JSON string. try use following:
data: '{"username":"'+ Email + '","password":"' + pwd + '"}'.
first try Restart your IIS
and pleas post your ASP code to check it i think you post parameter to get page or you don't use the authentication attributes
and the url you use is /logi !! is that right
i think wrong url it is /login
Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};
You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.
I have written a web method in ASP.net which it's output is an ArrayList of cities that is read from Sql server database.
this webmethod is called using Jquery in clientside.
but I don't know how to read each item of array list using jquery. for example every city and it's id equivalent.
Below is my Webmethod:
public ArrayList showcity(int s)
{
ArrayList list = new ArrayList();
String strConnString = ConfigurationManager
.ConnectionStrings["ConnectionCS"].ConnectionString;
String strQuery = "select ID, City from tbl_city where stateid=#s";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#s", s);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
list.Add(new ListItem(
sdr["City"].ToString(),
sdr["ID"].ToString()
));
}
con.Close();
return list;
}
}
and this is my clientside code:
function showcity() {
$.ajax(
{ url: "../AjaxServices/StateCity.asmx/showcity",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: '{s: ' + $('#<%=DpState.ClientID%>').val() + '}',
success: function(data) {
***// what should I write here to access every item separately***
},
error: function() { alert("Error"); }
})
}
If I use alert(data.d) I will get [object][object][object][object],.....
You need to create an actual type and return an array of that type. So create a City class, mark it serializable, build a List<City> in your loop, then return .ToArray(). The return type of your web method should be City[]
Instead of ArrayList being returned, it would be better to return an array with two dimension.
I found a solution myself so I share it here, just be careful about Value and Text they're case sensitive
success: function(data) {
$.each(data.d, function() {
alert(this['Value'] + ':' + this['Text']);
})
}