Sergejs
Sergejs

Reputation: 2580

Passing ViewModel to Action using jQuery

Is it possible to pass viewmodel to controllers action method calling it using jQuery? Currently in Action model is empty.

Controller:

    [HttpPost]
    public ActionResult Action(MyModel model)
    {
        ProcessModel(model);

        return Json(new
        {
            Result = "result"
        });
    }

jQuery:

function Serve() {
    $.ajax({
        type: "POST",
        url: "/Controller/Action",
        dataType: "json",
        error: function (xhr, status, error) {
            //Handle errors here...
        },
        statusCode: {
            404: function (content) { alert('Cannot find resource'); },
            505: function (content) { alert('Status code: 505'); },
            500: function (content) { alert('Internal server error'); }
        },
        success: function (json) {
            alert(json);

        }
    });

Thank you

Upvotes: 0

Views: 762

Answers (1)

Mark
Mark

Reputation: 6081

serialize the form data using api.jquery.com/serialize and the default MVC model binder will handle mapping form values to strongly typed models.

This works well as long as you ensure your form fields are either generated using strongly typed HTML helpers or match the named model properties:

@Html.TextBoxFor(model => model.PropertyName)

or

<input type="text" name="Model.PropertyName" />

Upvotes: 1

Related Questions