2013-05-02 49 views
0

我正在使用C#Web API接收具有选定倍数的表单的帖子。表单选择多个帖子到WebAPI

我在Web API方法模式是这样的:

{Model: { UserName: "Test", Groups: [ {Id:123}, {Id: 2}]}} 

换句话说,我的模型是某些领域的一类,也是一个复杂类型的数组。

的WebAPI正常工作,如果贴在表格的数据是:

UserName:Test 
Groups[0][Id]:123 
Groups[1][Id]:2 

但是,如果我序列化形式$(this).serialize()我得到的是这样的:

UserName:Test 
Groups[][Id]:123 
Groups[][Id]:2 

其中的WebAPI不能正确处理。

这是定义选择为:

<select name="Groups[][Id]" >...</select> 

我已经尝试过其他方法来定义选择,但我不能完成它。

我能够通过构建基于表单元素的对象并将对象传递给ajax而不是$(this).serialize来解决这个问题,但这是一个丑陋的黑客攻击。

WebAPI以某种方式支持接收来自表单的模型中的数组的属性?

谢谢。

回答

0

提交多选表单域的Web API,你可以使用所产生的数组值通过提交给Web API的表单以及您接受的控制器模型,可以将C#属性类型指定为string []。

实施例:

HTML:

<form> 
 
    <input id="regularTextInput" name="regularTextInput"> 
 
    <select multiple id="multiSelectField" name="multiSelectField"> 
 
\t \t <option>Option 1</option> 
 
\t \t <option>Option 2</option> 
 
\t \t <option>Option 3</option> 
 
\t </select> 
 
</form>

JS:

$.ajax({ 
 
    url: "http://localhost:####/api/MyController/DoSomething", 
 
    method: "POST", 
 
    data: { 
 
    singleVal: $('#regularTextInput').val(), 
 
    selectedVals: $('#multiSelectField').val() 
 
    }, 
 
    success: function(data, textStatus, jqXHR) { 
 
    console.log(data); 
 
    }, 
 
    error: function(jqXHR, textStatus, error) { 
 
    console.log(error); 
 
    } 
 
});

C#:

public class MyModel 
{ 
    [JsonProperty(PropertyName = "singleVal")] 
    public string MyVal { get; set; } 
    [JsonProperty(PropertyName = "selectedVals")] 
    public string[] MyVals { get; set; } 
} 

public class MyController 
{ 
    public JsonResult DoSomething([FromBody] MyModel model) 
    { 
     // You will have access to the form values here, including the strings selected from your multi-select field 
    } 
}