开发者

Problem on how to update the DOM but do a check on the data with the code-behind

This is with ASP.NET Web Forms .NET 2.0 -

I have a situation that I am not sure how to fulfill all the requirements. I need to update an img source on the page if selections are made from a drop down on the same page.

Basically, the drop downs are 'options' for the item. If a selection is made (i.e. color: red) then I would update the img for the product to something like (productID_red.jpeg) IF one ex开发者_JAVA百科ists.

The problem is I don't want to do post backs and refresh the page every time a selection is made - especially if I do a check to see if the image exists before I swap out the img src for that product and the file doesn't exist so I just refreshed the entire page for nothing.

QUESTION:

So I have easily thrown some javascript together that formulates a string of the image file name based on the options selected. My question is, what options do I have to do the following:

  • submit the constructed image name (i.e. productID_red_large.jpg) to some where that will verify the file exists either in C# or if it is even possible in the javascript. I also have to check for different possible file types (i.e. .png, .jpg...etc.).

  • not do a post back and refresh the entire page

Any suggestions?


submit the constructed image name (i.e. productID_red_large.jpg) to some where that will verify the file exists either in C# or if it is even possible in the javascript. I also have to check for different possible file types (i.e. .png, .jpg...etc.).

not do a post back and refresh the entire page

If you wish to not post back to the page you will want to look at $.ajax() or $.post() (which is just short hand for $.ajax() with some default options)

To handle that request you could use a Generic Http Handler.

A simple outline could work like the following:

jQuery example for the post:

$("someButton").click(function () {
    //Get the image name
    var imageToCheck = $("#imgFileName").val();
    //construct the data to send to the handler
    var dataToSend = {
        fileName: imageToCheck
    };
    $.post("/somePath/ValidateImage.ashx", dataToSend, function (data) {
        if (data === "valid") {
            //Do something
        } else {
            //Handle error
        }
    }, "html");
})

Then on your asp.net side you would create an http handler that will validate that request.

public class Handler1 : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        var fileName = context.Request["fileName"];
        var fullPath = Path.Combine("SomeLocalPath", fileName);

        //Do something to validate the file
        if (File.Exists(fullPath))
        {
            context.Response.Write("valid");
        }
        else
        {
            context.Response.Write("invalid");
        }

    }

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

Hope this helps, if I missed the mark at all on this let me know and I can revise.


We have an app of the same type, webforms .net 2, we do something similar with the following setup:

Using jQuery you can call a method in the page behind of the current page, for example, the following will trigger the AJAX call when the select box called selectBoxName changes, so your code work out the image name here and send it to the server.

$(document).ready(function () {
    $('#selectBoxName').change(function (event) {

        var image_name = 'calculated image name';

        $.ajax({
            type: "POST",
            url: 'SomePage.aspx/CheckImageName',
            data: "{'imageName': '" + image_name + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert(msg);
            },
            error: function (a, b, c) {
                alert("The image could not be loaded.");
            }
        });

    });
});

Where SomePage.aspx is the current page name, and image_name is filled with the name you have already worked out. You could replace the img src in the success and error messages, again using jQuery.

The code behind for that page would then have a method like the following, were you could just reutrn true/fase or the correct image path as a string if needed. You can even return more complex types/objects and it will automatically send back the proper JSON resposne.

    [System.Web.Services.WebMethod(true)]
    [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public static bool CheckImageName(string imageName)
    {
        /*
         * Do some logic to check the file


        if (file exists)
        return true;

        return false;
         */
    }

As it is .net 2 app, you may need to install the AJAX Extensions:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en


Could you not use a normal ajax call to the physical path of the image and check if it returns a 404?

Like this:
http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax



<script type="text/javascript">
    function UrlExists(url) {
        var http = new XMLHttpRequest();
        http.open('HEAD', url, false);
        http.send();
        return http.status != 404;
    }

    function ConstructImage() {
        var e = document.getElementById("opt");
        var url = '[yourpath]/' + e.value + '.jpg';
        if (!UrlExists(url)) {
            alert('doesnt exists');
            //do stuff if doesnt exist
        } else {
            alert('exists');
            //change img if it does
        }
    }

</script>
<select id="opt" onchange="ConstructImage()">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
</select>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜