What is the best method for sending a DbGeography parameter to MVC?

I am working on developing an API that allows users to save polygons on the server using ASP.NET MVC 5. Can anyone guide me on how to properly format the AJAX parameters for posting requests with DbGeography? This is what I have tried so far:

$.ajax({
    url: '/api/map',
    type: 'POST',
    data: {
        Title: 'My Title',
        MyGEOG: {
            WellKnownText: 'POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))'
        }
    }
});

Here is my MVC action method signature:

    [HttpPost]
    [Route("map")]
    public JsonResult Post(MyShape newShape) {...}

In addition, here's my MyShape class:

public class MapShape
{
    public string Title { get; set; }
    public System.Data.Entity.Spatial.DbGeography MyGEOG { get; set; }
}

When debugging the action, I notice that newShape.Title correctly displays as My Title, but MyGEOG is null during the AJAX post request. Can someone advise on the correct parameter format to successfully post as a DbGeography type?

Answer №1

The DBGeography object is designed to be immutable, meaning that once it is created, you cannot modify its properties. This becomes an issue when trying to instantiate the MapShape class in the model binder and finding the MyGEO property to be null, essentially attempting to set a property on a null object.

If you need to create a DBGeography object, you must utilize one of the factory methods such as:

FromText - Generates a new DbGeometry value using the specified well-known text representation. http://msdn.microsoft.com/en-us/library/hh673669(v=vs.110).aspx

To pass both the Title and WellKnownText values to your controller, I recommend creating a Data Transfer Object (DTO) to serve as a middleman for the data.

public class MapShapeDTO
{
    public string Title { get; set; } 
    public string WellKnownText { get; set; }
}

Your AJAX call can be simplified like so:

$.ajax({
url: '/api/map',
type: 'POST',
data: {
    Title: 'My Title',
    WellKnownText: 'POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))'
    }
});

In your controller, you can then use the DTO to construct the MapShape object.

[HttpPost]
[Route("map")]
public JsonResult Post(MapShapeDTO dto)
    {
        MapShape m = new MapShape()
            {
                Title = dto.Title,
                MyGEOG = System.Data.Entity.Spatial.DbGeography.FromText(dto.WellKnownText)
            };
      ...
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieving success seems to be out of reach

Can you help me achieve a successful data transmission conclusion? I have tried different methods, but none seem to work. When clicking the "Send" button, the data gets sent, but instead of the message saying "Data sent successfully," I need the form to di ...

What is the best way to maintain data types of variables within an object sent via ajax?

I'm sending an object via ajax to a PHP script for processing. Here's how I'm doing it: var Obj = {id:1, name:"John", value:12.1}; $.ajax({ url : "myfile.php", type : 'POST', data : Obj, success : ...

How to align two <select> elements side by side using Bootstrap

The issue I am encountering is that these two select elements within the same control-group are being displayed vertically when I want them to be displayed horizontally. I attempted using inline-block in CSS, but there are other <div> elements with ...

What is the reason for index always being not equal to 0?

<script> var index = 0; $.getJSON("./data/data.json", function(json) { $.each(json, function(data) { var html = ""; if(index == 0) { console.log(index + " fir ...

Issue Encountered: Problem with Implementing Google Fonts in WordPress Theme

I am currently facing an issue with a function in my Wordpress theme's functions file that is supposed to add Google Fonts to the theme. However, I keep receiving the following error message: Parse error: syntax error, unexpected '=', expec ...

Trigger price update in jquery based on radio or checkbox selection and specific conditions

https://i.sstatic.net/OIvgF.png In my product form, I have implemented a feature where selecting the "product type" and "product size" will update the price. However, if the user changes the product type after selecting the size, the price does not update ...

Looking to combine cells within a table using the Exceljs library

Encountered an issue while generating a worksheet in the EXCELJS library. function save_export(){ var workbook = new ExcelJS.Workbook(); var worksheet = workbook.addWorksheet('sheet', { pageSetup:{paperSize: 9, orientation:' ...

Default cross-origin behavior of the Fetch API

According to the Fetch Specifications, the default Fetch mode is 'no-cors'. The specifications state that a request's mode can be "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless otherwise specified, it defaults to "no ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Tips for including subjects in JSON data

I am trying to include the subject in JSON data so that I can fetch it using $.each(data.subject). Below is my API code where I am retrieving all the data encoded in JSON format. Any assistance would be greatly appreciated. [{"id":"79","FirstName":"Elon", ...

I have encountered a problem with ejs-mate where I am experiencing an issue with the <%- layout("path") %> command. Even though the path is accurate, it is not functioning correctly

Error Message: Unable to locate file at 'D:\Web Projects\major\views\listings\layouts\boilerplate.ejs' I have made numerous attempts to resolve this issue, but unfortunately, I keep encountering the same error. I ha ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...

ajax data submission and truncating sign problem

I need to include the ampersand '&' symbol in text when sending it via ajax to a PHP file. I tried using encodeURIComponent() like so: url: "add_process.php", data: "title="+ encodeURIComponent(title) +"& stages="+ values1, success: fu ...

Using database queries to populate a series of interconnected drop-down menus

Currently, I am facing an issue with my 2 drop-down menus. The first one is populated with possible continents, and the second should display countries based on the continent selected in the first menu. However, all countries are showing up in the dropdown ...

Choose an element based on its position in the index (multiple elements with the same class)

Can you use Javascript or jQuery to select an element by its index? For example: <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> If I have 4 elements with ...

Storing complex data structures in Firebase using VUEX

I am struggling to properly store my 'players' data within my team data structure. Currently, it is being saved with the team id but I need it to be nested inside of teams. Essentially, I want the players to seamlessly integrate and be appended ...

`Carousel nested within tabbed interface`

I am currently facing an issue with my website's tabs and carousels. I have 4 tabs, each containing a carousel, but only the carousel in the first tab seems to be working properly. When I activate the second tab, all the carousel divs collapse. For r ...

Is it possible for an ajax request to complete even if a page redirection occurs?

In my current project, I am attempting to generate a temporary URL for a local image and submit it to Google for an Image Search. I need this URL to be transient and automatically deleted after the search is complete. Here's the code snippet that I ha ...

Vue.js is unable to render the template using Object

During this demonstration at https://jsfiddle.net/ccforward/fa35a2cc/, I encountered an issue where the template could not render and the data in resultWrong remained empty with a value of {} At https://jsfiddle.net/ccforward/zoo6xzc ...

The Typescript module in question does not contain any exported components or functions related to

I've encountered an unusual issue while working on a React, Redux TypeScript application. It seems that after making some changes, one of the modules has stopped exporting its members. Here is the folder structure: src |---- components |---- contain ...