NovaDev
NovaDev

Reputation: 2971

jQuery post data to webapi

My question is two-fold: 1. When sending data from client to my webapi controller, do the names have to be the same?

If I have my model like this:

public class Donation
{
    public string DonorType { get; set; }
    //etc
}

But my form on my webpage is like this:

<div class="button-group grid-x align-center" id='sz-gift-source-group'>
    <a class="hollow button cell small-6" id="sz-donate-individual" sz-data-toggle-button required>A family or individual</a>
    <a class="hollow button cell small-6" id="sz-donate-corporate" sz-data-toggle-button>A business or company</a>
</div>

With my event handler like this:

$('form button[type=submit]').on('click', () => {
    const donation = getDonation();

    $.post(
        '//localhost:61012/api/Donation',
        $("#sz-donate-form").serialize(),
        (data) => {
            console.log(`post succeeded:[${JSON.stringify(data)}]`); 
        })
        .fail((data) => {
            console.log(`post failed:[${JSON.stringify(data)}]`);
        })
        .always((data) => {
            console.log(`post complete:[${JSON.stringify(data)}]`);
        });

    return false;
});

And secondly, what do I need to do to get the data from the form to the Donation object?

The tutorials I've looked at all seem to miss my first question, and part of what I'm wondering is if I've got an incomplete form here...

Upvotes: 0

Views: 33

Answers (1)

hmahdavi
hmahdavi

Reputation: 2354

Note that you must for serialize data's a form put your inputs inside form tag such as :

<form action="/" method="post" id="sz-donate-form">
    <input name="DonorType" type="text">
</form>

Note when you use serialize() form data serialized by inputs name attribute!

The name attribute should be same with Donation class property.

I think that you used typescript.

Your javascript code should be right.

Please post your action code in webapi to guid for it.

Upvotes: 1

Related Questions