我可以通过C#将结果返回给ajax

时间:2015-04-03 20:24:16

标签: c# jquery ajax

我有一些代码将内部html传递给C#后面的代码,负责将其存储到数据库中。现在我想将一些结果返回给ajax函数,它将帮助我在有条件的情况下呈现页面。 这是ajax函数和后面的代码 你可以在ajax的成功方法中看到我正在渲染到“list.aspx”

我想要在C#

内处理的条件下进行渲染

我想根据这个条件呈现页面

的Ajax

$('#Button1').click(function () {


                    var HTML = document.getElementById("data").innerHTML;
                       var Fname = document.getElementById("MyText").value;
                      Senddata = { "HTML": HTML, "Fname": Fname };
                    $.ajax({
                        type: "Post",
                        url: "/wwwroot/Default.aspx/save",
                        data: JSON.stringify(Senddata),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
                            console.log(result);
                            //    alert("Records Added");
                            window.open("List.aspx", "_self")
                            //    window.location = result;
                        }
                    });
                }
            });

C#代码

[WebMethod(EnableSession = true)]         public static void save(字符串HTML,字符串Fname)         {

    HttpContext.Current.Session["GUID"] = Convert.ToString(Guid.NewGuid());

    try
    {
       ............
        {
            con.Open();
        }

        string tempUser = Convert.ToString(HttpContext.Current.Session["UserID"]);

        if (string.IsNullOrEmpty(tempUser))
        {
            tempUser = "0";
        }

   ....................

      .
        con.Close();
 if (tempUser == "0")
                        {


                            HttpContext.Current.Response.Redirect("login.aspx");

                        }
                        else
                        {


                            HttpContext.Current.Response.Redirect("list.aspx");
                        }

    }
    catch (Exception ex)
    {
        CommonBLL.WriteExceptionLog(ex, "Form Save Default.aspx");
        throw ex;
    }
}

1 个答案:

答案 0 :(得分:1)

    This is how your c# code should look like. Let's discuss in chat if you have more questions.

    //change the return type to string
    [WebMethod(EnableSession = true)]
    public static string save(string HTML, string Fname) 
    {            

    ....

    try
    {
        ....

        if (string.IsNullOrEmpty(tempUser))
        {
            tempUser = "0";
            return "some value 1";
         }

        ....

        con.Close();  
        return "some value 2";
    }
    catch (Exception ex)
    {
        CommonBLL.WriteExceptionLog(ex, "Form Save Default.aspx");
        throw ex;
    }        
}