Announcement

Collapse
No announcement yet.

[CLOSED] [#177] jQuery Post Json

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • [CLOSED] [#177] jQuery Post Json

    Suppose we have simple model like:

    class Person {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public bool IsValid() {
            return !(string.IsNullOrEmpty(this.FirstName) ||
                string.IsNullOrEmpty(LastName) ||
                string.IsNullOrEmpty(Phone));
        }
    }
    is there a way to post it as json? something like this:

    jQuery.Post("/api/persons", Person, (object obj, string str, jqXHR request) => {
        //...
    }, , "json");
    It seems that jQuery tries to process Person class and make data object from it, and throws error, the only working sample i have found is:

    jQuery.Post("/SubmitFeedback.ashx", new {
            FirstName = Model.FirstName,
            LastName = Model.LastName
        }, (object obj, string str, jqXHR request) => {
            // ...
    }, "json");
    Last edited by Daniil; 2015-04-14 @ 04:20 PM.

  • #2
    Hi @mac2000,

    That is an interesting scenario! Thank you for asking!

    At this moment, the best thing we can suggest is to define such a method in the Person class
    public object ToObject()
    {
        return new
        {
            FirstName = this.FirstName,
            LastName = this.LastName
        };
    }
    and use it when needed
    jQuery.Post("url", person.ToObject(), ...);
    In the future we should be able to come up with a better solution. Created a feature request:
    https://github.com/bridgedotnet/Bridge/issues/177
    Last edited by Daniil; 2015-04-14 @ 05:54 PM.

    Comment


    • #3
      Yes, we can come up a built in solution. I'll put some time into this.

      Maybe a .ToLiteral() Method would be a better name.
      Last edited by geoffrey.mcgill; 2017-09-08 @ 05:33 PM.

      Comment


      • #4
        JSON.Stringify(person) appears to be a solution.
        public static void Main()
        {
            var person = new Person
            {
                FirstName = "Ivan",
                LastName = "Ivanov"
            };
        
            Console.Log(JSON.Parse(JSON.Stringify(person)));
        
            jQuery.Post("/api/persons", JSON.Stringify(person), ...);
        }
        Yes, JSON.Stringify() doesn't return an object, but it returns a JSON string which should be fine for jQuery.Post().

        If there is a need to get a plain object rather than a string, then this works:
        JSON.Parse(JSON.Stringify(person))
        Last edited by geoffrey.mcgill; 2017-04-12 @ 04:39 AM.

        Comment


        • #5
          Updated Issue #177 with a few options.

          Comment

          Working...
          X