user2423434
user2423434

Reputation: 199

ASP.NET: Relative Path with Root Operator('~') in Client side

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;
    }

Upvotes: 0

Views: 462

Answers (1)

user2423434
user2423434

Reputation: 199

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;
}

Upvotes: 1

Related Questions