0

I've used scaffolding to generate a Controller class for Web API 2 in ASP.NET.

I'd like to post an object from a browser. This is the generated method running:

    // POST: api/MyObjects
    [ResponseType(typeof(MyObject))]
    public async Task<IHttpActionResult> PostMyObject(MyObject myObject)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.MyObjects.Add(myObject);

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (MyObjectExists(myObject.Id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = myObject.Id }, myObject);
    }

I'm trying to invoke it from javascript/jquery:

$.post("http://localhost:2239/api/UrlVisits/5", "=" + "something");

My question is, what do I put in for "something" to serialize it correctly? When the method is entered, myObject is a valid object with all fields set to null. I don't know where in the stack this serialization is happening, so I'm not sure how to modify my post to fix it.

1 Answer 1

2

You need to change up the structure a bit.

First, /5 signifies an ID of 5, which doesn't make sense with the compound object your method is expecting.

Second, you don't need to manually specify any URL parameterization with "=". Both jQuery and WebAPI will handle those pieces for you if you structure your object correctly. WebAPI 2 is significantly more powerful when it comes to deserializing complex objects than it's predecessor. Simply post the object.

$.post("http://localhost:2239/api/UrlVisits", {id:1, name:"test name"});

Finally, you can use the [FromBody] attribute to specify that your object will be posted on the form body.

[ResponseType(typeof(MyObject))]
public async Task<IHttpActionResult> PostMyObject([FromBody]MyObject myObject)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that worked. The /5 was a copy-paste error. Incidentally, do you know what I should put in the javascript object for a field of type datetime in the database?
Glad to help :). You can use var d = new Date(); in Javascript. Just make sure you serialize to a DateTime type in your C# object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.