kk_nou
kk_nou

Reputation: 103

Bind System.Data.Entity.Spatial.DbGeography to MVC Model

I have an MVC model with a DBGeometry field

    [Required(AllowEmptyStrings = false, ErrorMessage = "Location is required")]
    public System.Data.Entity.Spatial.DbGeography LocationGps { get; set; } // LocationGPS

Inside my View i have this hidden values.

 @Html.HiddenFor(model => model.LocationGps)
 @Html.HiddenFor(model => model.Lat)
 @Html.HiddenFor(model => model.Lng)

When I edit the model I write the following to my Controller

   model.LocationGps = Utils.Geography.ConvertLatLonToDbGeography(model.Lng, model.Lat);
  if (ModelState.IsValid)
  {}

ConvertLatLonToDbGeography code:

   public static DbGeography ConvertLatLonToDbGeography(double longitude, double latitude)
    {
        var point = string.Format("POINT({1} {0})", latitude, longitude);
        return DbGeography.FromText(point);
    }

But ModelState is always Invalid because LocationGps is null. how can I set properly values to my LocationGps parameter through my View? The consept is to have a google map, get the coords from javascript (stored in Lat & Lng fields) and then set my LocationGps properly. How can I do that?

Upvotes: 0

Views: 306

Answers (1)

kk_nou
kk_nou

Reputation: 103

My problem solved with these steps:

  1. Add a JSonConverter inside my Model (JsonConverter found here)

    [JsonConverter(typeof(DbGeographyConverter))]
    [Required]
     public System.Data.Entity.Spatial.DbGeography LocationGps { get; set; }
    
  2. Serialize my datatable (server side)

    string json = JsonConvert.SerializeObject(dataTableData);
    return Json(json, JsonRequestBehavior.AllowGet);
    
  3. called JSON.parse (client side) because my dataSrc has other values except from list of results

       "ajax":
                {
                    "url": "@string.Format("{0}",Url.Content("~/Location/AjaxGetLocations"))",
                    "type": "POST",
                    "dataSrc": function (data) {
                        var json = JSON.parse(data);
                        return json["data"];
                    }
                },
      "columns": [
                { "data": "LocationID", "orderable": false, "visible": false },
                { "data": "LocationInternalCode", "orderable": false },
                { "data": "LocationName", "orderable": false },
        etc....
    

    I post it to save others from time. Very disappointed that no one had an answer to my question once again...

Upvotes: 0

Related Questions