Question

I have Industry type in my database. When it is null, it is showing an error like:

"Nullable object must have a value."

I want my value to display empty when it is null too.

This is my code:

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

Anyone have an idea? Please help me...

Was it helpful?

Solution

It is similar to "von v"'s answer, but I think the error of "Nullable object must have a value." can be from IndustryId since is nullable, so it is good to check for that first:

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

In my view it is good to do this

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.

OTHER TIPS

Check that an industry is returned first then write the name if there's any

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

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

Is IndustryId nullable? Then you can do this

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

and in the GetIndustry method, you can just return null if the id is zero.

public Industry GetIndustry(int id) {
    if (id==0) return null;
    // else do your stuff here and return a valid industry
}

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;

Please try something along the lines of

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

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top