Question

I have a JSON array like so:

theFormData = {"FormNodeID":142365,"SubmissionMethod":"Desktop","ConfirmationEmailID":"142371","FirstName":"Solomon","LastName":"Closson","EmailAddress":"myemail@testing.com","Company":"TIF","JobTitle":"Web Developer"}

FormNodeID, SubmissionMethod, and ConfirmationEmailID will always be the same, however, FirstName, LastName, EmailAddress, Company, and JobTitle are being populated into JSON with javascript as a string that will change according to the value that the Administrator has put into a Label, and uses a regex to remove the special chars and spaces.

So, I have code that populates this into another variable, called theProperty and than I add these JSON objects to it like so:

theFormData[theProperty] = value;

where value equals the inputs value. The thing is, I need to be able to transfer this JSON variable into an ASP.NET C# Class File .cs and build the class properties dynamically from the JSON Objects. Is this possible?

Right now am sending it to a Handler with the following code:

var formdata = 'formdata=' + encodeURIComponent(Sys.Serialization.JavaScriptSerializer.serialize(theFormData));
MakeRequest('/handlers/formshandler.ashx?f=formcontrol&r=' + Math.random(), 'POST', formdata, SaveComplete, null);

The MakeRequest and it's dependency Functions look like this:

function MakeRequest (url, verb, data, func, obj) {
    try {
        var TheRequest = new Sys.Net.WebRequest();

        TheRequest.set_url(url);
        TheRequest.set_httpVerb(verb);

        if (data) {
            TheRequest.set_body(data);
        }
        TheRequest.set_userContext(new RequestParamsNew(func, obj));
        TheRequest.add_completed(MakeRequestComplete);
        TheRequest.invoke();

        return TheRequest;
    }
    catch (error) {
        if (func) func('Communication Error');
    }
}
function MakeRequestComplete (executer, eventArgs) 
{
    var TheParams = executer.get_webRequest().get_userContext();

    if (executer.get_responseAvailable()) 
    {
        TheParams.responseData = executer.get_responseData().replace(/\u2028/g, '');
    }
    else 
    {
        TheParams.responseData = null;
    }
    if (TheParams.func) TheParams.func(TheParams);
}

function RequestParamsNew(afunc, obj) 
{
    this.func         = afunc;
    this.responseData = null;
    this.obj          = obj;
    this.Error        = null;
}

This passes it to a Form Handler located in handlers/formhandler.ashx

In this file, I check the request of f and than grab the posted formdata like so:

CustomForm theCustomForm = new JavaScriptSerializer().Deserialize<CustomForm>(_Context.Request["formdata"]);

So CustomForm is a Class file that I need to be able to populate the properties exactly from that of the formdata JSON variable. This doesn't seem to do this. It seems to be able to get the values, but I have to have the public properties set within the CustomForm.cs file Manually inputted in the .cs file. But instead, I need it to create the properties based on the JSON automatically, because the properties will most likely be different for different forms.

How is this possible to do?

EDIT

Ok, so now using Dictionary<string, string> instead of a class as per comments on this.

In the handler, now using this code:

List<string> theErrors = new List<string>();

Dictionary<string, string> theCustomForm = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(_Context.Request["‌​formdata"]);

foreach (KeyValuePair<string, string> pair in theCustomForm)
{
    theErrors.Add(pair.Key + " = " + pair.Value);
}

_Context.Response.Write(new
{
    Valid = theErrors.Count == 0,
    Errors = theErrors,
    Message = "Form Submitted"
}.ToJson());

Just testing to see if any Errors are returned at all. My SaveComplete function looks like this:

function SaveComplete(params) {
    if (params.responseData) {
        var theItems = eval(Sys.Serialization.JavaScriptSerializer.deserialize(params.responseData, false));

        if (theItems.Valid) {
           // Redirect somewhere...
           document.location.href = "http://www.google.com";
        }
        else {
            $.each(theItems.Errors, function (idx, error) {
                Console.Log(error);
            });
        }
    }
}

But I get the following Error:

Sys.ArgumentException: Sys.ArgumentException: Cannot deserialize. The data does not correspond to valid JSON.
Parameter name: data

If I change theItems part in the SaveComplete function to this:

var theItems = params.responseData;
alert(theItems);

It alerts the following (a 500 Page Error):

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->

<head>
  <title>PHL</title>
  <meta name="description" content="" />
  <meta name="keywords" content="" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="viewport" content="width=1024" />
  <meta charset="utf-8" />

  <link rel="shortcut icon" href="/media/1606636/homestead_favicon.ico" type="image/x-icon" />
  <link rel="stylesheet" href="/scripts/jquery-select2/select2.css" />
  <!-- <link rel="stylesheet" href="styles/bootstrap.css" /> -->
  <link rel="stylesheet" href="/styles/datepicker.css" />
  <link rel="stylesheet" href="/styles/styles.css" />

  <script type="text/javascript" src="//use.typekit.net/qrs7pfm.js"></script>
  <script type="text/javascript">      try { Typekit.load(); } catch (e) { }</script>

  <script type="text/javascript" src="/scripts/BaseUI.js"></script>
</head>
<body>
  <div class="var-nav" style="display: none;"></div>
  <div id="Container" class="secondary">

    <!-- Header -->
    <div class="header-elements clearfix">
      <div class="header-row row">
        <header class="header container">
          <div class="main-nav nav-small">
            <div class="clearfix">
              <nav>
                <ul class="nav-buttons">
                  <li class="phl-logo"><a href="/">PHL</a></li>
                  </li>
                </ul>
              </nav>      
            </div>
          </div>
        </header>
      </div>
      <div id="call-phl">1-800-CALL-PHL</div>
    </div>
    <!-- .Header -->


    <div id="hero-slideshow" class="hero-slideshow">
      <div class="slides">
        <div class="slide">
          <img src="/images/SAMPLE_slide-grad-bg.jpg" alt="" />
        </div>
      </div>
    </div>

    <div class="page tertiary bg_pattern">
      <div class="">
        <div class="row-inner breadcrumbs-row">
            <ul class="breadcrumbs clearfix">
            <li><a href="/">Home</a></li>
            <li>Error 500</li>
          </ul>        
        </div>          
        <div class="row-inner bg_pattern">
            <h1>Error 500: Internal Server Error</h1>
            <!-- Right Rail Column -->
            <div class="right-rail clearfix">
            <div class="body article-body">            
                <div class="article container">                
                <p>The server was unable to send the html document to you due to an internal (server software) error.</p>
                <p>If the issue persists, contact <a href="#">webmaster@discoverPHL.com</a></p>
              </div>
            </div>
            <div class="rail">
            </div>
          </div>
            <!-- Right Rail Column -->
        </div>
      </div>

    </div>


  </div>
  <!-- .Footer -->
</div>
</body>
</html>

This is coming from 500.htm file within the website root. Is there something in the web.config file that needs to be done for this that I'm missing perhaps?

Sys.Serialization.JavaScriptSerializer.serialize(theFormData) returns the JSON just fine, so it must be in the way it is being deserialized perhaps?

Was it helpful?

Solution

Problem is resolved with the following:

public void SubmitCustomForm()
{
    List<string> theErrors = new List<string>();

    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var dict = serializer.Deserialize<Dictionary<string, string>>(_Context.Request["formdata"]);

    foreach (KeyValuePair<string, string> pair in dict)
    {
        theErrors.Add(pair.Key + " = " + pair.Value);
    }

    _Context.Response.Write(new
    {
        Valid = theErrors.Count == 0,
        Errors = theErrors,
        Message = "Form Submitted"
    }.ToJson());            
}

This validates perfectly fine with no errors. Not sure why the other approach didn't work, but this atleast works perfect now and lets me handle the Dictionary items...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top