0

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;
    }
2
  • Can you give us some of your code? Otherwise we can't help you. Commented Aug 10, 2015 at 3:03
  • you need to give folder structure of your project Commented Aug 10, 2015 at 4:27

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.