如何使用三元运算符检查将值绑定到控件的输入字段

How to bind the value to input field to a control by using ternary operator check

我有一些输入控件,我试图通过检查无效的 null 来绑定值

<input id="LastKnownLatitudeDegree" name="VesselMissing.LastKnownLatitudeDegree" value="@Model.VesselMissing != null ? @Model.VesselMissing.LastKnownLatitudeDegree : ''" class="form-control" max="89" min="0" step="1" type="number" data-dec="0"><span>&#176;</span>

如果我在控件顶部使用空检查,则用户无法看到输入数据

@if (@Model.VesselMissing != null)
{
   <input id="LastKnownLatitudeDegree" name="VesselMissing.LastKnownLatitudeDegree" value="@Model.VesselMissing.LastKnownLatitudeDegree" class="form-control" max="89" min="0" step="1" type="number" data-dec="0"><span>&#176;</span>
}

我有一些这样的控件需要绑定值字段。我尝试了另一种方法,但我想知道是否有可能按照第一个语句

这可行,但我有大约 20 个控件,所以我正在考虑让它按照第一个状态运行

@{
     string LastKnownLatitudeDegree = string.Empty;
     if(Model.VesselMissing !=null)
     {
         LastKnownLatitudeDegree = Model.VesselMissing.LastKnownLatitudeDegree;
     }
 }
     <input id="LastKnownLatitudeDegree" name="VesselMissing.LastKnownLatitudeDegree" value="@LastKnownLatitudeDegree  class="form-control" max="89" min="0" step="1" type="number" data-dec="0"><span>&#176;</span>

在这两种情况下你都有语法错误。

<input id="LastKnownLatitudeDegree" name="VesselMissing.LastKnownLatitudeDegree"
    value="@(Model.VesselMissing != null ? Model.VesselMissing.LastKnownLatitudeDegree : "")" /> 

@if (Model.VesselMissing != null)
{
   <input id="LastKnownLatitudeDegree" name="VesselMissing.LastKnownLatitudeDegree" value="@Model.VesselMissing.LastKnownLatitudeDegree" class="form-control" max="89" min="0" step="1" type="number" data-dec="0"><span>&#176;</span>
}