开发者

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

if I wan开发者_运维百科t 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


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.


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.


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


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜