Reputation: 913
Good day,
I have an asp.net mvc4 project where I tried declare variable in jquery. Problem to be concluded in next: my data get from the model @Model.EducationProgramBachelorId
and the property EducationProgramBachelorId
in my class declared as int?
. And when i try declare it in my jquery code:
var progId = @Model.EducationProgramBachelorId;
R# told me that int? University.EducationProgramBachelorId Syntax Error
I need this variable in my if/else
condition where i want to do next:
if(progId != null){
//Do something
}
else{
//Do something
}
My questions is:
How can I declare int?
variable in jquery?
In if
statement when it's true
I need write just return
for that my function is closed or something else?
EDIT
Here is the part of my RAZOR page:
@model Models.Entities.University
@Html.DropDownList("EducationProgramBachelorId", String.Empty)
@Html.ValidationMessageFor(model => model.EducationProgramBachelorId)
<script type="text/jscript">
$(document).ready(function () {
var progId = @Model.EducationProgramBachelorId; //here is I have an error and function didn't work
if(progId != null){
return;
}
else{
$.getJSON('/Administrator/ProgramList/' + 1, function (data) {
var items = '<option>Select a Program</option>';
$.each(data, function (i, program) {
items += "<option value='" + program.Value + "'>" + program.Text + "</option>";
});
$('#EducationProgramBachelorId').html(items);
});
}
});
</script>
Upvotes: 1
Views: 2297
Reputation: 133403
You can try,
var progId = @(Model.EducationProgramBachelorId.HasValue ? Model.EducationProgramBachelorId : 0);
Thus if Model.EducationProgramBachelorId
is null its progId
will be set to 0
Upvotes: 1
Reputation: 31345
If a nullable int?
property is rendered to the view, it will not output anything. Can you create a new property in your model that will convert the int?
to a normal int? Then return a zero if the EducationProgramBachelorId variable is null.
public int EducationProgramBachelorJSInt
{
get
{
return EducationProgramBachelorId.HasValue ?
EducationProgramBachelorId.Value : 0;
}
}
Then your JQuery code will look like this.
var progId = @Model.EducationProgramBachelorJSInt;
if(progId != 0){
//Do something
}
else{
//Do something
}
Upvotes: 1