2015-12-22 29 views
1

我有一個頁面,張貼如下形式(這是一個簡單的HTML表單):形式系列化

public class PlacesModel 
{ 
    public Dictionary<string, Dictionary<string, int>> Point { get; set; } 
} 

point[location1][x]:10 
point[location1][y]:20 
point[location2][x]:40 
point[location2][y]:60 

在動作我可以使用下面的模型獲取表單值

Beeing動作:

[HttpPost] 
public ActionResult GetPoints(PlacesModel model) 
{ 
    // do something with the model here 

    return View(); 
} 

不過,我寧願使用不同的模型,如檢索表單值:

public class PlacesModel 
{ 
    public Dictionary<string, Coord> Point { get; set; } 
} 

public class Coord 
{ 
    public int x { get; set; } 
    public int y { get; set; } 
} 

但這不起作用。 字典中充滿了2個條目,一個用於「location1」,另一個用於「location2」,但coord對象從未初始化。

對此有何看法?

回答

1

您可以按自己想要的方式將您自己的自定義模型綁定器綁定到PlacesModel。更多關於如何使用模型陪同人員都在這太問題:

ASP.Net MVC Custom Model Binding explanation

我相信,默認模式粘結劑你想要的PlaceModel工作,您的標記應該是這個樣子:

<input type="text" name="point[0].Key" value="location1" /> 
<input type="text" name="point[0].Value.x" value="10" /> 
<input type="text" name="point[0].Value.y" value="20" /> 

根據由Scott Hanselman的博客文章http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

+0

這是一個有效的答案。但在走這條道路之前,我正在試着看看我是否缺少可以用我創建模型的方式完成的事情。 – Gnomo

+0

你能顯示你生成的輸入標記是什麼樣子嗎? (查看錶單字段的id和name屬性的值? –

+0

那麼,對我來說,解決方案是基於Scott Hanselman提供的。我所做的是將輸入名稱從點[location1] [x ]到點[location1] .x之類的東西 – Gnomo

0

你能嘗試樓盤X與字符串類型,

public class Coord 
{ 
    public string x { get; set; } 
    public int y { get; set; } 
} 

因爲表單項的第二個索引中的x,y是字符串,並且當您使用int類型的Coord.x時,模型聯編程序將預期爲整數。