Jquery declare int?变量在 asp.net MVC4 中
本文关键字:asp net MVC4 变量 declare int Jquery | 更新日期: 2023-09-27 18:31:02
美好的一天,
我有一个 asp.net mvc4 项目,我尝试在 jquery 中声明变量。接下来要解决的问题:我的数据来自模型@Model.EducationProgramBachelorId
和我的类中声明为 int?
的属性EducationProgramBachelorId
。当我尝试在我的jquery代码中声明它时:
var progId = @Model.EducationProgramBachelorId;
R#告诉我int? University.EducationProgramBachelorId Syntax Error
我在if/else
条件下需要这个变量,接下来要做:
if(progId != null){
//Do something
}
else{
//Do something
}
我的问题是:
如何在 jquery 中声明
int?
变量?在
if
语句中,当它true
我需要写return
,因为我的函数是关闭的还是别的什么?
编辑
这是我的RAZOR页面的一部分:
@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>
如果将
可为 null 的 int?
属性呈现到视图,则它不会输出任何内容。您可以在模型中创建一个新属性,将int?
转换为普通 int?然后,如果 EducationProgramBachelorId 变量为 null,则返回零。
public int EducationProgramBachelorJSInt
{
get
{
return EducationProgramBachelorId.HasValue ?
EducationProgramBachelorId.Value : 0;
}
}
那么你的 JQuery 代码将如下所示。
var progId = @Model.EducationProgramBachelorJSInt;
if(progId != 0){
//Do something
}
else{
//Do something
}
你可以
试试,
var progId = @(Model.EducationProgramBachelorId.HasValue ? Model.EducationProgramBachelorId : 0);
因此,如果Model.EducationProgramBachelorId
为空,则其progId
将设置为 0