Reputation: 135
I'm trying to pass a property of my model to an AJAX form but since the bool resolves as "true/false" I'm encountering problems.
$.ajax({
url: '/Projects/SearchTable2',
type: "GET",
data: {
sub_num: @Model.SubmissionNumber,
read_only: @Model.ReadOnly,
}
});
Model.ReadOnly
resolves to either true or false which throws an Uncaught ReferenceError: False is not defined
when I try to execute the code. Is there a workaround for this, or another way I can pass the variable to the Controller method?
Upvotes: 0
Views: 2324
Reputation: 5062
@Model.ReadOnly
render as a Capital Boolean (True)
and JavaScript has no idea about it, so just change your code to it:
$.ajax({
url: '/Projects/SearchTable2',
type: "GET",
data: {
sub_num: @Model.SubmissionNumber,
read_only: @Model.ReadOnly.ToString().ToLower(),
}
});
Upvotes: 2
Reputation: 218852
When razor executes the code in the view, It will output the below code to the browser
read_only: True,
Assuming @Model.ReadOnly
returns boolean true.
In C# boolean value is either True
or False
, but in js, it is lower case true
or false
So when browser's javascript framework try to execute this code, It does not treat True
as true
. It thinks True is a js variable. But since we did not define it earlier, we are getting the "True is not defined" error!
What you have to do is, convert the boolean value produced by C# code to something which js understands. Call ToString()
and call ToLower
which will convert True
to true
$.ajax({
url: '/Projects/SearchTable2',
type: "GET",
data: {
sub_num: @Model.SubmissionNumber,
read_only: @Model.ReadOnly.ToString().ToLower(),
}
});
Upvotes: 0