Gnomo
Gnomo

Reputation: 419

Form serialization in c#

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?

Upvotes: 1

Views: 289

Answers (2)

mehmet mecek
mehmet mecek

Reputation: 2685

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 .

Upvotes: 0

Vilius K.
Vilius K.

Reputation: 68

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

Upvotes: 1

Related Questions