3

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 
5
  • 1
    what data type is @Model.Company? Commented Jan 28, 2013 at 22:11
  • Just a remark: you can use "@Url.Action("Action", "Controller")" instead of "/Controller/Action". (msdn.microsoft.com/en-us/library/dd492874(v=vs.108).aspx) Commented Jan 28, 2013 at 22:16
  • Well, still the most likely problem with your code presented here. Do you get any errors? Commented Jan 28, 2013 at 22:16
  • Could well be because the model property company is a class object and needs to be serialized first. Also, If you are getting something with the Ajax call based on the Company, do you need to pass everything? Would it not be enough to just pass something like: data: {CompanyId: @Model.Company.Id} or similar? Then all you need in your controller action is the int CompanyId paramter. Commented Jan 28, 2013 at 22:23
  • You can't just pass the Model definition because they're not exactly data that is useful to the server. You need to serialize the Form when the form is submitted. It's either you convert it to a JSON format or Serialize the Model object as a whole. Commented Jan 28, 2013 at 22:26

1 Answer 1

7

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);
        }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.