【问题标题】:Jquery declare int? variable in asp.net mvc4Jquery声明int? asp.net mvc4中的变量
【发布时间】:2013-09-12 15:58:23
【问题描述】:

早安,

我有一个 asp.net mvc4 项目,我尝试在 jquery 中声明变量。接下来要结束的问题:我的数据来自模型@Model.EducationProgramBachelorId,我的类中的属性EducationProgramBachelorId 声明为int?。当我尝试在我的 jquery 代码中声明它时:

var progId = @Model.EducationProgramBachelorId;

R# 告诉我int? University.EducationProgramBachelorId Syntax Error

我需要在我的if/else 条件中使用此变量,我接下来要执行此操作:

if(progId != null){
//Do something
}
else{
//Do something
}

我的问题是:

  1. 如何在 jquery 中声明int? 变量?

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

【问题讨论】:

  • 你不需要在javascript中将变量声明为int。你在哪里看到错误?它看起来根本不像是 javascript 错误。
  • 是 ReSharper 告诉您有错误,还是编译器或运行时告诉您有错误? ReSharper 可能会出错。
  • 在这行代码 var progId = @Model.EducationProgramBachelorId 之后我有红色波浪线有我的错误
  • @BorHunter 是 .js 文件还是 asp.net 页面中的那一行?我们需要更多信息。在我看来,这应该在一些 javascript 中,但它不是。
  • @BorHunter:过去我遇到过问题,Visual Studio 无法理解视图中的 Razor 代码和 JavaScript 代码的混合。但这并不妨碍它实际工作。代码是否编译?它运行吗?是否存在实际错误或只是智能感知错误?

标签: c# jquery asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

如果一个可以为空的int? 属性被渲染到视图,它不会输出任何东西。你能在你的模型中创建一个新属性,将int? 转换为普通的int吗?如果 EducationProgramBachelorId 变量为空,则返回零。

public int EducationProgramBachelorJSInt
{
    get
    {
        return EducationProgramBachelorId.HasValue ? 
        EducationProgramBachelorId.Value : 0;
    }
}

那么您的 JQuery 代码将如下所示。

var progId = @Model.EducationProgramBachelorJSInt;
if(progId != 0){
    //Do something
}
else{
    //Do something
}

【讨论】:

  • 谢谢你,你的回答很棒,对我很有帮助
  • @BorHunter 当然!很高兴我能帮上忙。
【解决方案2】:

你可以试试,

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

因此,如果Model.EducationProgramBachelorId 为空,则其progId 将设置为0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多