通过字符串数组作为参数传递给ASP.NET MVC的WebAPI方法 [英] pass string array as parameter to asp.net mvc webapi method

查看:135
本文介绍了通过字符串数组作为参数传递给ASP.NET MVC的WebAPI方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用webapi2,这里是我的客户端code

I am using webapi2 and here is my client side code

var tbody = $('#files-table').find('tbody'); // tbody where all rows exists 
        var sortOrder = $(tbody).sortable('toArray').toString(); // geting ids of all rows 
        var updateSortOrder = $.ajax({
            url: baseUrl + 'mycontroller/updateimagesorder',
            dataType: 'json',
            traditional: true,
            contentType: 'application/json',
            data: JSON.stringify({ "sortOrder": sortOrder.split(',') }),
            type: 'PUT'
        });
        updateSortOrder.done(function (result) {
            closeModel('images-model');
        });

和这里是我的服务器端方法

and here is my server side method

[Route("updateimagesorder")]
    public HttpResponseMessage PutImagesSortOrder([FromBody]string[] sortOrder) 
    {
       // do stuff with parameters 
     }

请注意: / myController的是路径preFIX在这里和的baseUrl 是我的域名网址

Note : /mycontroller is route prefix here and baseUrl is my domain url

那么,是什么在我的code中的问题?

so , what the issue in my code ?

推荐答案

尝试传递值是这样的:

data: JSON.stringify(sortOrder.split(',')),

这样你的请求负载看上去像一个字符串数组:

So that your request payload looks like a string array:

["foo", "bar"]

如果你想通过这样的值:

If you want to pass the value like that:

data: JSON.stringify({ "sortOrder": sortOrder.split(',') }),

然后确保您已声明一个视图模型:

then make sure that you have declared a view model:

public class MyViewModel
{
    public string[] SortOrder { get; set; }
}

这是你的控制器操作将作为参数:

that your controller action will take as parameter:

[Route("updateimagesorder")]
public HttpResponseMessage PutImagesSortOrder(MyViewModel model) 
{
    // do stuff with parameters 
}

这篇关于通过字符串数组作为参数传递给ASP.NET MVC的WebAPI方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆