Sarawut Positwinyu
Sarawut Positwinyu

Reputation: 5042

How use javascript as the argument in asp.net <%= %> script

The path is javascript path

    var fileName = args.get_fileName();
    lstImg.src = <%=GetListImageFilePath(fileName) %>

file name is error because it is javascript and not in .NET how to put this argument in .NET Code

Upvotes: 0

Views: 240

Answers (5)

gilly3
gilly3

Reputation: 91587

You'll need to use AJAX. One easy way to do it would be to use PageMethods. First, add a [WebMethod] attribute to your method:

[WebMethod]
protected static string GetListImageFilePath(string fileName)
{

This method must be static.

Then set EnablePageMethods="True" on your script manager. Then you can call your c# code from JavaScript like this:

var fileName = args.get_fileName();
PageMethods.GetListImageFilePath(fileName, function (path) {
    lstImg.src = path;
});

Upvotes: 3

Edi Wang
Edi Wang

Reputation: 3637

add an ashx(http handler) in your website, then you can use lstImg.src = '/example.ashx?name=' + fileName.

public class ExampleHandler: IHttpHandler {

    public void ProcessRequest (HttpContext context) {
    var request = context.Request;
        string fileName = (string)request.QueryString["name"];
        // your logic
        context.Response.Write(yourpath)
    }

    public bool IsReusable {
    get {
        return false;
    }
    }
}

Upvotes: 0

Narendra
Narendra

Reputation: 3117

I think get_fileName() is server side function. So you can call it from the HTML directly. Check these links

http://weblogs.asp.net/jalpeshpvadgama/archive/2012/01/07/asp-net-page-methods-with-parameters.aspx http://stackoverflow.com/questions/7633557/asp-net-is-it-possible-to-call-methods-within-server-tag-using-eval

If you call the javascript function using RegisterStartupScript() or RegisterClientScriptBlock() then these will be called in client side not in server side.

If you want to call the javascript function immediately in server side then declare an equivalent server side function.

Upvotes: 0

Anand
Anand

Reputation: 14945

You simply can not do it because javascript is running at client side i.e on browser where as server code run at server. What you could do is change the your GetListImageFilePath function so that it returns the base URL for your image directory and then append the file name to create the image path.

var fileName = args.get_fileName();
lstImg.src = <%=GetListImageFilePath() %> + '/' + fileName;

For more information, like how server tags in Javascript are processed, I have answered a StackOverFlow thread here. Please have a look to clarify your doubt.

Upvotes: 0

podiluska
podiluska

Reputation: 51504

You can't. The JavaScript runs on the client, and the asp.net code is on the server. You need to use some other way of communicating with the server eg: Ajax to a web service, a postback, etc

Upvotes: 1

Related Questions