0

I have a model class named Parcel. This parcel includes Name, CenterPoint parameters:

public class Parcel
{
    public string Name { get; set; }
    public object CenterPoint { get; set; }
}

I am getting theese parameters from a map. When I click a parcel center point is calculated and setted in a variable in javascript. CenterPoint is a json object. Name is a plain text data.

I want to save CenterPoint as Json object in database. And when I get CenterPoint again on map, I can draw it.

When I post data to action method as following, my CenterPoint object is coming like this {object}.

Actually it should be like this: { type="point", x=121.32380004076, y=452.024614968}

    [HttpPost]
    public ActionResult SaveParcel(Parcel parcel)
    {
        return Json(new {parcel}, JsonRequestBehavior.AllowGet);
    }

my javascript jode is here:

           var postata = {
                    "Name": document.getElementById("name").value,
                    "CenterPoint": document.getElementById("center").value
            };

            $http({
                method: 'POST',
                url: "/Parcel/SaveParcel/",
                data: postata,
            }).success(function (data, status, headers, config) {
                console.log(data);
            });

How can I save and get JSON as orginally. Or is there is a good way passible?

barteloma
  • 6,403
  • 14
  • 79
  • 173

1 Answers1

0

I think question is...will JSON deserializer convert your Point to an anonymous class (to put it inside a generic Object property)? AFAIK no: see this post for details (with a hand-made solution in case you really need it).

I would define a Location class:

public class Location
{
    public type { get; set; }
    public float x { get; set; }
    public float y { get; set; }
}

Then change Parcel to:

public class Parcel
{
    public string Name { get; set; }
    public Location CenterPoint { get; set; }
}

Please note "...inside a generic Object property...". Deserializer won't do that but Json.NET will do what you need for a dynamic object then you may rewrite your Parcel class to:

public class Parcel
{
    public string Name { get; set; }
    public dynamic CenterPoint { get; set; }
}
Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208