Elim99
Elim99

Reputation: 673

ASP.NET MVC Passing model to controller with AJAX

I'm trying to pass a model to my controller with an ajax call.

I've looked at the answer provided by Laviak in the following question but was not able to get it to work.

Possible Answer

I'm getting an undefined error with the MODEL variable when the ajax call runs. I've confirmed that the helper class is being called and is returning a string. Is it because the AJAX call is inside a .js file? Why is it undefined?

My Code:

Site.Master:

<script type="test/javascript">   
    var MODEL = '<%= Model.ToJson() %>';
</script>

Helper Class:

public static string ToJson(this Object obj) 
    {
        string model = new JavaScriptSerializer().Serialize(obj);
        return model; 
    } 

Javascript file:

    var GstTotal = $.ajax(
{
    type: 'POST',
    async: false,
    url: BASE_APP_URL + 'WashTicket/GetTaxTotal',
    traditional: true, //This setting is required to pass arrays to the Controller
    //        data: MODEL
    data: {
        aModel: MODEL
    }
}).responseText;

Action method:

        public string GetTaxTotal(string aModel)
    {

        return "";
    }

Upvotes: 2

Views: 9831

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Make sure that the javascript file that is containing the AJAX call is included after the script that defines the MODEL variable in your master file:

<script type="test/javascript">   
    var MODEL = '<%= Model.ToJson() %>';
</script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/myscript.js") %>"></script>

Also I would recommend you taking a look at the following article which illustrates how to pass complex object graphs using JSON AJAX request to a controller.

Upvotes: 3

Related Questions