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 "";
}
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 "";
}
Share
Improve this question
edited May 23, 2017 at 12:06
CommunityBot
11 silver badge
asked Oct 26, 2011 at 23:15
Elim99Elim99
6733 gold badges18 silver badges34 bronze badges
1 Answer
Reset to default 3Make 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 remend you taking a look at the following article which illustrates how to pass plex object graphs using JSON AJAX request to a controller.