2013-05-02 52 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 
    } 
}