Stewie Griffin
Stewie Griffin

Reputation: 9317

passing key/value pairs from javascript to C# code behind

if I want to pass key/value pairs from javascript to C# ASP.NET code behind, should I use querystring parameters, hidden value or other methods? Values are not from the form, so jquery serialize or params() won't work..I guess I have to serialize it manually?? Values come from dropdownlist (name/selected option text) pairs

Upvotes: 1

Views: 3877

Answers (5)

Matt Ghafouri
Matt Ghafouri

Reputation: 1577

I had the same issue. I solve it by something like this :

I prepare my array inside of a foreach loop in JavaScript

var itemIdVersionCollection = [];
var itemName = row[1];
var version  = row[2];
var key = { Key: itemId , Value: version };
itemIdVersionCollection.push(key);

My Model was something like this :

public class IdVersion
{
    public int? Key { get; set; }
    public string Value { get; set; }
}

public class SomeModel 
{
   public List<IdVersion> ItemIdVersion { get; set; } 
}

The action :

Public ActionResult MethodName(SomeModel model)

Upvotes: 0

MackPro
MackPro

Reputation: 308

You can achieve this by having a hidden server tag and include an onclientclick attribute on your postback button(s).

<input id="hdnKV" runat="server" />
<asp:Button id="btnSubmit" runat="server" onclientclick="selectKeyValues();" onclick="btnSubmit_OnClick">Submit</asp:Button> 

This onclientclick javascript function would populate this hidden value from your key value pairs.

function selectKeyValues() {

    var kv= getKeyValues(),
        hiddenValue = document.getElementById('<%= hdnKV.ClientID =>');

    hiddenValue.Value = kv;

}

It's not stated what data you have but you can probably use the following format for keyvalue pairs.

key1=value1,key2=value2,key3=value3

Upvotes: 0

smartcaveman
smartcaveman

Reputation: 42246

The easiest, most universally compatible way to do this is by appending the key-value-collection to the querystring. It will be available in ASP.NET from HttpContext.Request.QueryString.

That being said, there are a variety of ways to accomplish your goal. You could send an $.ajax request using the serialized values. If you want to get the serialized values in jQuery by serializing the form, you can add elements to the form prior to serializing.

Upvotes: 1

Keith
Keith

Reputation: 43024

That's what JSON is for. Most Javascript frameworks have JSON serializer built-in. Probably C# has a JSON module as well (but I don't know). You could also use XHR to send it.

Upvotes: 2

Tim Almond
Tim Almond

Reputation: 12686

probably best to pass it as JSON and then use a JSON library (or WCF) to convert it

Upvotes: 0

Related Questions