0

Industry我在我的数据库中有类型。当它为空时,它显示如下错误:

“可空对象必须有一个值。”

我希望我的值在为空时也显示为空。

这是我的代码:

<p>
    <strong>Industry Type:</strong>
    <%: Model.GetIndustry(Model.IndustryId.Value).Name%>
</p>

有人有想法吗?请帮我...

4

5 回答 5

0

检查是否先返回一个行业,如果有,请写下名称

<%
  var industry = Model.GetIndustry(Model.IndustryId.Value);
%>

<%: industry == null ? "" : industry.Name %>

可以为IndustryId空吗?然后你可以这样做

<%
    var industry = Model.GetIndustry(Model.IndustryId.GetValueOrDefault(0));
%>

在该方法中,如果 id 为零GetIndustry,则可以返回。null

public Industry GetIndustry(int id) {
    if (id==0) return null;
    // else do your stuff here and return a valid industry
}
于 2013-05-06T11:26:40.663 回答
0

它类似于“von v”的答案,但我认为“Nullable object must have a value”的错误。可以来自 IndustryId,因为它可以为空,所以最好先检查一下:

 <p>
    <strong>Industry Type:</strong>
    <%:if(Model.IndustryId.HasValue)
    {
      var idustry =  Model.GetIndustry(Model.IndustryId.Value);
      if(industry!= null)
        industry.Name
    }
    else
    {
    ""
    }
%>        
</p>

在我看来,这样做很好

Model.GetIndustry()

in Back end, like controller, and then return the industry by viewstate, like checking in the:

string industryName = "";
     if(Industry.IndustryId.HasValue){
    var industry = YourClass.GetIndustry(Industry.IndustryId.Value);
    industryName = industry!= null ? Industry.Name : "" ;
}
ViewBag.IndustryName= industryName;

and then use your ViewBag in view like this:

<p>
    <strong>Industry Type:</strong>
    <%: ViewBag.IndustryName %>
</p>

It is good to separate the checking from view and do the logics in code.

Hope it helps.

于 2013-05-06T11:51:43.160 回答
0

string can accept null or empty value, why don't you try string.IsNullOrEmpty(Model.IndustryId.Value)

this is pretty self explanatory. in your controller,

  string yourValue = string.empty;
  yourValue = Model.GetIndustry(Model.IndustryId.Value).Name;

  if(string.IsNullOrEmpty(yourValue))
  {
     //display your result here!
  }

  ViewBag.IndustryValue = yourValue;
于 2013-05-06T12:47:39.530 回答
0

Please try something along the lines of

<p>
    <strong>Industry Type:</strong>
    <%: Model.IndustryId.HasValue ? Model.GetIndustry(Model.IndustryId.Value).Name : string.Empty%>
</p>
于 2013-05-07T00:33:32.010 回答
0

I found the Problem.

 <p>
    <strong>Industry Type:</strong>
    <% if (Model.IndustryId.HasValue)
      { %>
     <%: Model.GetIndustry(Model.IndustryId.Value).Name%>

     <%}
      else
      { %>
     <%:Model.IndustryId==null ? "": Model.GetIndustry(Model.IndustryId.Value).Name %>
     <%} %>
    </p>
于 2013-05-07T05:42:33.030 回答