sterix24
sterix24

Reputation: 2400

I can't seem to post my form values back to the server

I'm playing around with MVC3 and trying to create a simple contact form that posts the values back to the server using jquery $.ajax.

At the moment my View for my contact form binds to a ContactViewModel I've created:

public class ContactViewModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    public string Message { get; set; }     
}

Here is my [HttpPost] method for handling the posted form once it's been submitted:

    [HttpPost]
    public ActionResult SubmitForm(ContactViewModel contactVM)
    {
        if (!ModelState.IsValid)
        {
            return View(contactVM);
        }

        // TODO: If the form's valid then save the data

        return RedirectToAction("Thankyou");
    }

As you can see, this method expects a ContactViewModel datatype. I was rather confused as it seems I don't have this class available in my javascript so I figured I'd have to rebuild the class in js then post this back to my SubmitForm method? Below is the code I've used to try and achieve this:

<script type="text/javascript">
    $(document).ready(function () {
        var contactVM = { ContactViewModel : [{
            Name: $('#Name').val(),
            Email: $('#Email').val(),
            Message: $('#Message').val() }]
        };

        $.ajax({
            url: '/Contact/SubmitForm',
            type: "POST",
            data: JSON.stringify(contactVM),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function () {
                alert('Success!');
            },
            error: function () {
                alert('Failure!');
            }
        });
    });        
</script>

As you can see, I've tried to create the exact same class in javascript so that I can post it back to the server but when I step through the code, it seems that my the contactVM variable accepted in the SubmitForm method only has null values.

Where am I going wrong? Am I even on the right track here? Apologies if I haven't explained this very clearly!

Thanks!

UPDATE: Turns out I was being an idiot and only calling the the $.ajax function page load instead of when the button was clicked! Combined with what Andrew said below, all seems to be working :-)

Upvotes: 1

Views: 113

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

In this case, there's no need for the "wrapper" ContactViewModel in the JavaScript. You should be able to simply write:

$(document).ready(function () {
    var contactVM = {
        Name: $('#Name').val(),
        Email: $('#Email').val(),
        Message: $('#Message').val()
    };

    $.ajax({
        url: '/Contact/SubmitForm',
        type: "POST",
        data: JSON.stringify(contactVM),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            alert('Success!');
        },
        error: function () {
            alert('Failure!');
        }
    });
});     

The model binder will take the object you submit and map it to a ContactViewModel.

Upvotes: 1

Related Questions