通过jQuery将params object []传递给C#方法

时间:2014-08-01 18:20:52

标签: c# jquery reflection invoke

我试图通过jQuery将params object[]传递给C#方法。我使用它通过jQuery调用使用相同的方法,发送一个字符串,这将是真正的调用方法,params object[]是这个调用的参数,显然参数的数量是未知的,因为我不知道究竟会调用什么方法,这里是jQuery上的代码:

$('#selectComboBox').change(function () {
    var data = {
        'method': 'GetComboBoxValues',
        'arguments': $.param({ Id: this.value })
    };
    LoadComboBox('/Get/GetJsonResult', data, $('#destionationComboBox'))
})

LoadComboBox函数是一个简单的函数,我居中填充组合框:

function LoadComboBox(url, data, select) {
    select.empty();

    $.getJSON(url, data, function (a) {
        $(a).each(function () {
            $(document.createElement('option')).prop('value',this.Value).text(this.Text).appendTo(select);
        });
    });
}

我的C#代码如下:

public string GetJsonResult(string method, params object[] arguments)
{
    var methodInfo = this.GetType().GetMethod(method);

    var l = methodInfo.Invoke(this, arguments);

    return new JavaScriptSerializer().Serialize(l);
}

我将参数作为对象数组获取,并且填充了字符串Id=1$('#selectComboBox').value1)。我无法在新数组中执行Split('='),因为如果真实方法(GetComboBoxValues)不期望字符串(在这种情况下是INT),它将不会动态转换。

有人有任何提示或线索吗?

2 个答案:

答案 0 :(得分:1)

这是一个非常有趣的问题。看起来您的主要问题是从一个对象数组动态转换为一组动态选择的方法所需的参数类型。简而言之,可以使用methodInfo.GetParameters();并使用Convert.ChangeType将每个参数转换为相应的ParameterType来完成此操作。这可能是最好的行动,所以我做了一个小型的表单应用程序来做到这一点。当然,这一切都有很多假设,传入的内容将是“干净的”,因此很多错误处理可能都是有序的。

private void button1_Click(object sender, EventArgs e)
{
    //mock up some dynamically passed in parameters
    var testParams = new List<object>();
    testParams.Add("1");
    testParams.Add("Hello");

    //the args I'm building up to pass to my dynamically chosen method
    var myArgs = new List<object>();

    //reflection to get the method
    var methodInfo = this.GetType().GetMethod("test");
    var methodParams = methodInfo.GetParameters();

    //loop through teh dynamic parameters, change them to the type of the method parameters, add them to myArgs
    var i = 0;
    foreach (var p in methodParams)
    {
        myArgs.Add(Convert.ChangeType(testParams[i], p.ParameterType));
        i++;
    }

    //invoke method
    var ans = methodInfo.Invoke(this, myArgs.ToArray());

    //display answer
    MessageBox.Show((string)ans);
}

public string test(int i, string s)
{
    return s + i.ToString();
}

顺便说一下,在我看来,这会导致一些难以维护的疯狂代码(你正在尝试用C#做事,而这并不是真正意义上的事情)。但你并没有真正问过任何人的意见,所以我会把它留在一边。

答案 1 :(得分:0)

Mike Bell引导我回答,他的想法只需要一些调整,下面评论,答案是编辑Get JsonResult方法,对此:

public string GetJsonResult(string method, params object[] arguments)
{
    var methodInfo = this.GetType().GetMethod(method);
    var methodParameters = methodInfo.GetParameters();

    var parameters = new List<object>();

    for (int i = 0; i < methodParameters.Length; i++)
    {
        //  Here I'm getting the parameter name and value that was sent
        //  on the arguments array, we need to assume that every
        //  argument will come as 'parameterName=parameterValue'
        var pName = arguments[i].ToString().Split('=')[0];
        var pValue = arguments[i].ToString().Split('=')[1];

        //  This way I can get the exact type for the argument name that I'm sending.
        var pInfo = methodParameters.First(x => x.Name == pName);

        parameters.Add(Convert.ChangeType(pValue,
            //  This is needed because we may be sending a parameter that is Nullable.
            Nullable.GetUnderlyingType(pInfo.ParameterType) ?? pInfo.ParameterType));
    }

    var l = methodInfo.Invoke(this, parameters.ToArray());

    return new JavaScriptSerializer().Serialize(l);
}
相关问题