1

I have a page that posts the following form (this is a simple html form):

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

In an action I can obtain the form values using the following model:

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

Beeing the action:

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

    return View();
}

However, I would rather retrieve the form values with a different model such as:

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

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

But this doesn't work. The dictionary is filled with 2 entries, one for "location1" and one for "location2" but the coord object is never initialized.

Any thoughts on this?

Julien Poulin
  • 12,737
  • 10
  • 51
  • 76
Gnomo
  • 407
  • 4
  • 13

2 Answers2

1

You could write your own custom model binder for binding form to the PlacesModel the way you want. More on how to use model minders are on this SO question:

ASP.Net MVC Custom Model Binding explanation

I believe for default model binder to work with the PlaceModel you want, your markup should look something like this:

<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" />

according to blog post by Scott Hanselman http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

Community
  • 1
  • 1
Vilius K.
  • 68
  • 3
  • 8
  • That's a valid answer. But before going that path I'm trying to see if I'm missing something that can be done in the way I create my model. – Gnomo Dec 22 '15 at 12:09
  • Could you show what your generated input markup looks like? (i.e.what are the values for id and name attributes of your form fields? – Vilius K. Dec 22 '15 at 12:24
  • Well, for me the solution was based on the Scott Hanselman post provided. What I did was to change the input names from something like point[location1][x] to something like point[location1].x – Gnomo Dec 22 '15 at 15:24
0

Can you try property x with string type,

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

Because x, y 's in the second index of form items are strings, and model binder will expect integers when you use int type of Coord.x .

mehmet mecek
  • 2,615
  • 2
  • 21
  • 25