Manikandan Sethuraju
Manikandan Sethuraju

Reputation: 2893

Pass the Dictionary data to Controller string method using jquery post

My Jquery code is given below

 $("#btnExec").live('click', function () {
       var data1= "lorem ipsum";
       var data2= "lorem ipsum";
       var data3= "lorem ipsum";
       var dict = new Object();

       $("#ArgsTable tr").each(function (e) {
                var firstTD = $(this).find("td").eq("0").html().trim().replace(/\s/g, "");
                var secondValue = $(this).find("td").eq("1").find("input:text").val();
                dict[e] = [firstTD,secondValue]; 
       });

       $.ajax({
                type: 'POST',
                cache: false,
                data: { strdata1: data1, strdata2: data2, strdata3: data3, myDictionary: dict },    
                url: '<%=Url.Action("ExecData","Home") %>',
                success: function (data) {        
                }
              });
 });

And my controller method is given below

public string ExecData(string strdata1, string strdata2, string strdata3,  Dictionary<object, object> myDictionary)
{
    //do some stuff...
}

If i click btnExec means, its fired the controller method with string values properly, but the dictionary values come always null ..

In my scenario "the return type of controller method should be string only"

How can i solve this? Thanks in advance !!!

Upvotes: 4

Views: 11876

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

Tyr like this:

[HttpPost]
public ActionResult ExecData(
    string strdata1, 
    string strdata2,  
    string strdata3, 
    Dictionary<string, string> myDictionary
)
{
    return Content("hello world");
}

and then:

var data = {
    strdata1: 'lorem ipsum',
    strdata2: 'lorem ipsum',
    strdata3: 'lorem ipsum'
};

$('#ArgsTable tr').each(function (index, item) {
    var firstTD = $(this).find('td').eq(0).html().trim().replace(/\s/g, '');
    var secondValue = $(this).find('td').eq(1).find('input:text').val();
    data['myDictionary[' + index + '].Key'] = firstTD;
    data['myDictionary[' + index + '].Value'] = secondValue;
});

$.ajax({
    url: '<%=Url.Action("ExecData","Home") %>',
    type: 'POST',
    traditional: true,
    data: data,
    success: function (result) {

    }
});

Upvotes: 6

Related Questions