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
5 Answers
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.
2 Comments
addQueryParam(key, value[,index]). The source of the string manipulation can be found at code.google.com/p/jsuri/source/browse/jsuri.js#328 .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
1 Comment
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)