Riddick
Riddick

Reputation: 1318

MVC4 Ajax- Pass complete model to controller

I have my AJAX call

$.ajax({
    type: 'post',
    url: "/Store/LoadStoreIndex",
    data: , //Entire Model Here!!
    dataType: "text",
    success: function (result) {
        $('#Postback').html(result);
    }
});

I need to send my entire model back to the controller, but after much searching can't find anything ... Can somebody show me what I need to be doing?

Upvotes: 0

Views: 6024

Answers (1)

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

Controller Get Action

public ActionResult Index(YourModel model)
{
    YourModel model = new YourModel();

    return View(model);
}

View

@model YourModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "form1" }))
{
    @Html.TextBoxFor(x => x.EmailAddress)
    @Html.TextBoxFor(x => x.Name)
    ...
}

Script

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                // you can post your model with this line
                data: $(this).serialize(),  
                beforeSend: function () {

                },
                complete: function () {

                },
                success: function (result) {

                },
                error: function () {

                }
            });
        }
        return false;
    });
});

Controller Post Action

[HttpPost]
public ActionResult Index(YourModel model)
{
    return View();
}

Upvotes: 3

Related Questions