user3645275 user3645275 - 5 months ago 7
HTML Question

Object being received as null from form POST

I am trying to call a URL to convert an object into an excel file to be downloaded by the client, so I am using the following HTML:

<form id="downloadAsExcelForm" style="display: none;" action="global/DownloadFile" method="POST">
<input id="downloadToken" type="hidden" name="token" value="" />
<input id="complexObject" type="hidden" name="complexObject" value="" />
</form>


Along with the following javascript:

var req = {
param1: "Example",
param2: 1,
param3: [ { attr1: "test", attr2: 1, attr3: "Hello" },
{ attr1: "test", attr2: 1, attr3: "Hello" },
{ attr1: "test", attr2: 1, attr3: "Hello" } ]
};

$("#downloadToken").val("nhwe1-jdw3e-djdw2-mkcds");
$("#complexObject").val(JSON.stringify(req));
$("#newQueryForm").submit();


And finally, the following Controller .cs:

public ActionResult DownloadFile(string token, wcfGlobal.complexObjectRequest complexObject)
{
...
}


The problem I am having is that the token is being received just fine (it is just a simple string); however, the complexObject is being received as null. Does anyone know how I could resolve this issue? I usually just use jQuery.ajax(...) for these types of requests, but given that I need to download the file directly, I don't have that option here.

Answer

You are serializing the req object before sending it, so it is sent as a string. There is not a way to automatically have the complexObject deserialized.

The way I see it you can keep sending the complex object as string and deserialize it in the controller

HTML

<form id="downloadAsExcelForm" style="display: none;" action="global/DownloadFile" method="POST">
    <input id="downloadToken" type="hidden" name="token" value="" />
    <input id="complexObject" type="hidden" name="complexObjectStr" value="" />
</form>

C#

// Required reference
using System.Web.Script.Serialization;

public ActionResult DownloadFile(string token, string complexObjectStr)
{
    wcfGlobal.complexObjectRequest complexObject = new JavaScriptSerializer().Deserialize<wcfGlobal.complexObjectRequest>(complexObjectStr);

    // Now complexObject has the values you sent from the browser
}

Based on the JavaScript you posted the complexObjectRequest class needs to be declared like this

public class complexObjectRequest
{
    public string param1 { get; set; }
    public int param2 { get; set; }
    public List<Param3> param3 { get; set; }

    public complexObjectRequest()
    {

    }
}

public class Param3
{
    public string attr1 { get; set; }
    public string attr2 { get; set; }
    public string attr3 { get; set; }

    public Param3()
    {

    }
}
Comments