虽然成功返回

时间:2018-02-28 04:19:00

标签: javascript c# asp.net webmethod

我有一个带有C#代码的ASP.NET Web表单站点,从VS2013调用,在Win 10下运行并在Google Chrome中查看。我试图在Default.aspx标记中从Javascript调用C#函数,如下所示

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
     <textarea id="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
    <img id="imgPaste"  src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
    <asp:Button Text="Save" runat="server" OnClick="Save" />
     <input id="Text1" type="text" name ="ImageData"  hidden="hidden" />

<script type="text/javascript">
    window.onload = function () {
        document.getElementById('txtPaste').focus();
        document.getElementById('txtPaste').onpaste = function (event) {
            var items = (event.clipboardData || event.originalEvent.clipboardData).items;
            console.log(JSON.stringify(items));
            var blob = null;
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") === 0) {
                    blob = items[i].getAsFile();
                }
            }
            if (blob !== null) {
                var reader = new FileReader();
                reader.onload = function (event) {                  
                document.getElementById("imgPaste").src = event.target.result;
                document.getElementById("Text1").value = event.target.result;
                PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure); 
                };
                reader.readAsDataURL(blob);
            }
        }
    };
    function onSuccess(result) {
        alert("Success! " + result);
    }
    function onFailure(result) {
        alert("Failed! " + result);
    } 
</script>
</asp:Content>

PageMethod在Default.aspx.cs中定义:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Services;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Save(object sender, EventArgs e)
    {
        string str = Request.Form["ImageData"];
        SaveImg(str);
    }
    [WebMethod]
    public static bool SaveImg(string str)
    {
        try
        {
            string imageData = str.Replace("data:image/png;base64,", "");
            var bytes = Convert.FromBase64String(imageData);
            string filePath = @"C:\Windows\Temp\File.jpg";
            if (File.Exists(filePath)) File.Delete(filePath);
            using (var imageFile = new FileStream(filePath, FileMode.Create))
            {
                imageFile.Write(bytes, 0, bytes.Length);
                imageFile.Flush();
            }
            return false;
        }
        catch (Exception Ex)
        {           
                return true;
        }
    }
}

当我点击txtPaste并粘贴图像时,图像显示在imgPaste中,可以通过单击“保存”按钮下载为文件来执行SaveImg功能。

我试图仅通过粘贴图像来创建文件,而不是通过将SaveImg定义为Web方法并在填充Image控件后调用PageMethods.SaveImg来单击“保存”按钮。对SaveImg的调用显示和OnSuccess函数中指定的警告,但不执行SaveImg - 函数中设置的断点不会粘贴事件,尽管它们是单击“保存”按钮的情况。如果在Firefox中查看网站,则会显示相同的行为。

Master.aspx文件中的ScriptManager将EnablePageMethods设置为True。

我尝试了以下操作,以便在粘贴事件上执行SaveImg而不会成功:

1)注释掉settings.Config中的settings.AutoredirectMode使PageMethods.SaveImg返回失败状态。

2)在global.asax中评论一行或两行:

RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

3)使用如下所示的AJAX功能。 sParam被定义为event.target.result.toString(),并且调用替换了PageMethods.SaveImg调用

function showDetail(sParam) {       
        $.ajax({ 
            type: "POST", 
            url: "Default.aspx/SaveImg", 
            data: "{'str': '" +sParam +"'}", // passing the parameter 
            contentType: "application/json; charset=utf-8", 
            dataType: "json", 
            success: function(retValue) {
                // Do something with the return value from.Net method
            } 
        }); 

1 个答案:

答案 0 :(得分:0)

在ASP.Net中从Javascript调用C#函数可以通过将C#函数放在控件的click事件中然后从Javascript调用控件的click事件来完成,如下所示: / p>

页面标记中的JavaScript:

%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
     <textarea id="txtPaste" name="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
    <img id="imgPaste"  src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
    <asp:Button Text="Save" runat="server" OnClick="cmdSave_Click" ID="cmdSave" />
     <input id="Text1" type="hidden" name ="ImageData"  hidden="hidden" />

<script type="text/javascript">
    window.onload = function () {
        document.getElementById('txtPaste').focus();
        document.getElementById('txtPaste').onpaste = function (event) {
            var items = (event.clipboardData || event.originalEvent.clipboardData).items;
            console.log(JSON.stringify(items));
            var blob = null;
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") === 0) {
                    blob = items[i].getAsFile();
                }
            }
            if (blob !== null) {
                var reader = new FileReader();
                reader.onload = function (event) {                  
                document.getElementById("imgPaste").src = event.target.result;
                document.getElementById("Text1").value = event.target.result;
                //PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure);
                document.getElementById("txtPaste").value = "Image Pasted"
                document.getElementById("cmdSave").click();
                };
                reader.readAsDataURL(blob);
            }
        }
    };

</script>

C#代码:

protected void cmdSave_Click(object sender, EventArgs e)
    {
        string str = Request.Form["ImageData"];
        SaveImg(str);
    }
    public  bool SaveImg(string str)
    {
        try
        {
            string imageData = str.Replace("data:image/png;base64,", "");
            var bytes = Convert.FromBase64String(imageData);
            string filePath = @"C:\Windows\Temp\File.jpg";
            if (File.Exists(filePath)) File.Delete(filePath);
            using (var imageFile = new FileStream(filePath, FileMode.Create))
            {
                imageFile.Write(bytes, 0, bytes.Length);
                imageFile.Flush();
            }
            return false;
        }
        catch (Exception Ex)
        {           
                return true;
        }
    }