Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Never</strong> do that. <strong>Never</strong> build JSON manually. <strong>Always</strong> use JSON serializers. Or in your case you don't even need to do that because the ASP.NET webmethod runtime will take care. All you have to do is focus on your business requirements and don't worry about plumbing.</p> <p>So for example start by defining a model that will represent your data:</p> <pre><code>public class Person { public string FirstName { get; set; } public string LastName { get; set; } } </code></pre> <p>and then have your web method return this model leaving all serialization concerns to the framework:</p> <pre><code>[WebMethod] public static Person GetPerson() { Person p = new Person(); p.FirstName = "Manas"; p.LastName = "Tunga"; return p; } </code></pre> <p>And now simply consume this method from the client:</p> <pre><code>$.ajax({ type: 'POST', url: 'simplePage.aspx/GetPerson', data: '{ }', contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.d.FirstName); alert(data.d.LastName); } }); </code></pre> <p>No need to worry about JSON, string builders, ...</p> <p>And you could also pass complex arguments to your web method if you needed to:</p> <pre><code>public class Foo { public string Bar { get; set; } } </code></pre> <p>and then:</p> <pre><code>[WebMethod] public static Person GetPerson(Foo foo) { ... } </code></pre> <p>and finally:</p> <pre><code>$.ajax({ type: 'POST', url: 'simplePage.aspx/GetPerson', data: JSON.stringify({ foo: { bar: 'baz' } }), contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.d.FirstName); alert(data.d.LastName); } }); </code></pre> <p>The <code>JSON.stringify</code> method shown here is natively built into modern browsers. If you need to support legacy browsers you could include the <a href="https://github.com/douglascrockford/JSON-js" rel="noreferrer">json2.js</a> script to your page.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload