Hanna
Hanna

Reputation: 10753

Sending ASP.NET Model through AJAX

I'm trying to send part of a model through an ajax call, but doing it simply like my code below, doesn't work. How could I pass this object along?

$.ajax({
            url: "/Controller/Action",
            type: "GET",
            data: @Model.Company,
            success: function (result) {
            $('#myDiv').html(data);
        }
});

This is what my JS puts outs:

MyProj.Domain.Entities.Company

This is my error:

Uncaught ReferenceError: MyProj is not defined 

Upvotes: 3

Views: 186

Answers (1)

Dave Alperovich
Dave Alperovich

Reputation: 32500

Your syntax would work fine for a primitive variable, but you should serialize your object to Json before sending. And also make sure that script stays in cshtml or aspx page, else '@Html' helper will not work.

$.ajax({
            url: "/Controller/Action",
            type: "GET",
            data: @Html.Raw(Json.Encode(Model.Company)),
            success: function (result) {
            $('#myDiv').html(data);
        }
});

Upvotes: 7

Related Questions