convert context.Request.Params to C# properties in generic handler

2k views Asked by At

I am using jquery ajax with generic handle to submit my record to sql server 2012 database but my code "List PP" returning null value so that i can not insert data in database table. I want to add JSON.stringify values in c# properties and insert it into database. Here is my code sample

Jquery ajax

var P = {};
              P.PatnerFormsName = $("[id*=txtpatnername]").val();
              P.PatnerFormsAddress = $("[id*=txtaddress]").val();
              var fileUpload = $("#Upload").get(0);
              var files = fileUpload.files;
              var test = new FormData();
              for (var i = 0; i < files.length; i++) {
                  test.append(files[i].name, files[i]);
              }
              test.append("P",  JSON.stringify(P) );

              $.ajax({
                  url: "UploadHandler.ashx",
                  type: "POST",
                  contentType: false,
                  processData: false,
                  data: test,
                  // dataType: "json",
                  success: function (result) {
                      alert(result);
                  },
                  error: function (err) {
                      alert(err.statusText);
                  }
              });

Properties Class:

public class Properties
{

    // Insertion Area Start //

    // Patner Form Start //
    public string PatnerFormsName { get; set; }
    public string PatnerFormsAddress { get; set; }

}

Generic Handler

public void ProcessRequest (HttpContext context) {



        if (context.Request.Files.Count > 0)
        {
            Properties P = new Properties();
            JavaScriptSerializer js = new JavaScriptSerializer();
            var param = context.Request.Params["P"];
            List<Properties> PP = new List<Properties>();

            PP = (List<Properties>)js.Deserialize(param, typeof(List<Properties>));

            foreach (var item in PP)
            {
                context.Response.Write(item.PatnerFormsAddress);
               using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "sp_test";
                    cmd.Connection = Getconnected.getconnecting();
                    cmd.Parameters.AddWithValue("@Name", P.PatnerFormsAddress);
                    cmd.Parameters.AddWithValue("@Address", P.PatnerFormsAddress);
                    cmd.ExecuteNonQuery();
                }

            }


            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                string fname;
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = "Logo" + file.FileName;
                }

                fname =Path.Combine(context.Server.MapPath("~/Images/Patner/"), fname);
                file.SaveAs(fname);


            }
        }

    }
2

There are 2 answers

4
kblau On

Please make the following changes. Please let me know if you need additional help.

This is similar to what you are doing, and notice how data is passed.

var parms = {
    "viewModel": "adding",
    "operation": "delete"
};


$.ajax({
    //took out alot of items
    url: "UploadHandler.ashx",
    type: "POST",
    cache: false,
    data: parms,
    success: function (result) {
        alert(result);
    },
    error: function (err) {
        alert(err.statusText);
    }
});

Here is my handler and I am accessing the parameters different:

context.Request.Params["viewModel"]
"adding"
context.Request.Params["operation"]
"delete"
3
kblau On

First of all in App_Start RouteConfig, your code should look like this

public static void RegisterRoutes(RouteCollection routes)
{
    //routes.EnableFriendlyUrls();

    var settings = new FriendlyUrlSettings();
    settings.AutoRedirectMode = RedirectMode.Off; // RedirectMode.Permanent
    routes.EnableFriendlyUrls(settings);
}

Your web.config, would have an element for handler

<system.web>
  <httpHandlers>
    <add verb="*" path="UploadHandler.ashx" type="FredWebForm.UploadHandler,FredWebForm"/>
  </httpHandlers>

Your Handler could look like this

public class Properties
{
    // Insertion Area Start //
    // Patner Form Start //
    public string PatnerFormsName { get; set; }
    public string PatnerFormsAddress { get; set; }
}

/// <summary>
/// Summary description for UploadHandler
/// </summary>
public class UploadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //please put a breakpoint here to see values
        var name = context.Request.Params["Name"];
        var address = context.Request.Params["Address"];
        //Browser security restrictions will not allow the path to the multiple
        //files selected.  You can do the select ONE file and pass the byte stream.
        //Also, doing multiple files will NOT pass the byte stream
        //I would allow one file at a time.  Please let me know and I will show you.
        var theFiles = context.Request.Params["TheFiles"].Substring(0, context.Request.Params["TheFiles"].Length - 1);
        var theFilesSplit = theFiles.Split(',');
    }

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

Your aspx looks like this

<%@ Page ValidateRequest="false" Language="C#" AutoEventWireup="true" CodeBehind="AddingHandler.aspx.cs" Inherits="FredWebForm.AddingHandler" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        var handleFiles = function (event) {
            for (var i = 0; i < event.target.files.length; i++) {
                $("#theFiles").val($("#theFiles").val() + event.target.files[i].name + ",");
            }
        };
        $(function () {
            $("#theButton").click(function () {
                var P = {};
                P.PatnerFormsName = $("[id*=txtpatnername]").val();
                P.PatnerFormsAddress = $("[id*=txtaddress]").val();
                //var fileUpload = $("#Upload").get(0);
                //var files = fileUpload.files;
                //var test = new FormData();
                //for (var i = 0; i < files.length; i++) {
                //    test.append(files[i].name, files[i]);
                //}
                //test.append("P", JSON.stringify(P));
                var parms = {
                    "Name": P.PatnerFormsName,
                    "Address": P.PatnerFormsAddress,
                    "TheFiles": $("#theFiles").val()
                };
                $.ajax({
                    //took out alot of items
                    url: "UploadHandler.ashx",
                    type: "POST",
                    cache: false,
                    data: parms,
                    success: function (result) {
                        alert(result);
                    },
                    error: function (err) {
                        alert(err.statusText);
                    }
                });
            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p id="demo"></p>
            <input type="text" id="txtpatnername" name="txtpatnername" value="Eddie Namey" readonly="readonly" />
            <br />
            <input type="text" id="txtaddress" name="txtaddress" value="107 E Johnson Way" readonly="readonly" />
            <p style="color: green" />
            Hit "Choose files" then
            <br />
            Highlight and select **more than one file** using Ctrl or Shift and mouse to select multiple files
            <br />
            then hit "Go"
            <br />
            <br />
            Select files:
            <input type="file" id="selectFiles" name="selectFiles" onchange="handleFiles(event)" multiple="multiple" />
            <%--this is need for chrome--%>
            <input type="hidden" id="theFiles" />
            <br />
            <br />
            <input type="button" value="Go" id="theButton" />
        </div>
    </form>
</body>
</html>