通过jQuery传递参数object[]到c#方法

本文关键字:方法 object jQuery 参数 通过 | 更新日期: 2023-09-27 18:15:56

我试图通过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),它将不会被动态转换。

有人有什么提示或线索吗?

通过jQuery传递参数object[]到c#方法

这是一个非常有趣的问题。似乎你的主要问题是动态地从对象数组转换到一堆所需的参数类型的动态选择的方法。简而言之,可以使用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#做一些它并不真正想做的事情)。但是你并没有真正征求任何人的意见,所以我把这个放在一边。

Mike Bell带领我找到了答案,他的想法只是需要一些调整,评论如下,答案是关于编辑GetJsonResult方法,到此:

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);
}