2

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 "";
    }

1 Answer 1

3

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.

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.