1

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:

  1. How can I declare int? variable in jquery?

  2. 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>
4

2 回答 2

1

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
}
于 2013-09-12T16:17:00.843 回答
1

You can try,

 var progId = @(Model.EducationProgramBachelorId.HasValue ? Model.EducationProgramBachelorId : 0);

Thus if Model.EducationProgramBachelorId is null its progId will be set to 0

于 2013-09-12T16:35:45.553 回答