我正在尝试将两个参数传递给以下函数,但我无法实现该函数:
public void SetShopSubCategories([FromBody]string userId, int []subCategories )
{
}
我是这样发帖的:
var subCategories = [ 1, 2, 3, 4, 5];
var userId = "123";
$.ajax({
type: "POST",
url: "/Category/SetShopSubCategories/",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(userId, subCategories),
success: function () {
alert("OK");
},
error: function () {
alert("error");
}
当我只使用一个参数发布时,一切顺利,我可以达到功能:
public void SetShopSubCategories([FromBody]string userId )
{
}
var userId = "123";
$.ajax({
type: "POST",
url: "/Category/SetShopSubCategories/",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(userId, subCategories),
success: function () {
alert("OK");
},
error: function () {
alert("error");
}
这个也不错:
public void SetShopSubCategories( int []subCategories )
{
}
var subCategories = [ 1, 2, 3, 4, 5];
$.ajax({
type: "POST",
url: "/Category/SetShopSubCategories/",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(subCategories),
success: function () {
alert("OK");
},
error: function () {
alert("error");
}
我的路由配置:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "SetCategories",
routeTemplate: "{controller}/{action}"
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
最佳答案
型号
public class Mymodel
{
public string UserId { get; set; }
public int[] subCategories { get; set; }
}
Controller Action
[HttpPost]
public void SetShopSubCategories([FromBody]Mymodel model)
{
}
Ajax 调用:
var subCategories = [1, 2, 3, 4, 5];
var userId = "123"
$.ajax({
type: "POST",
url: "/api/Values",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ userid: userId, subCategories: subCategories }),
success: function () {
alert("OK");
},
error: function () {
alert("error");
}
});
这是链接:http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
你会发现由于流的类型不允许使用多个参数或有问题。
关于C# web-api post 使用两个参数运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27500277/