0

I have a form in a Create view. When I try to display a certain field, I get NullReferenceException: Object reference not set to an instance of an object.. If I comment out the input control for ItemId, all is well. The label shows up, but obviously not the control.

Variety:

public class Variety
{
    [Key]
    public int ItemId { get; set; }

    public int SpeciesId { get; set; }
    public virtual Species species { get; set; }

    [DataType(DataType.Currency, ErrorMessage = "Please ender a currency value")]
    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)]
    public double Price { get; set; }

    [Required(ErrorMessage = "You must enter a variety.")]
    [Display(Name = "Variety")]
    public string VarietyName { get; set; }

}

InventoryItem:

public class InventoryItem
{
    [Key]
    [Display(Name = "Inventory Id")]
    public int InventoryId { get; set; }

    [Required(ErrorMessage = "Item Id Required")]
    [Display(Name = "Item Id")]
    public int ItemId { get; set; }
    public virtual Variety variety { get; set; }

    [Required(ErrorMessage = "Quantity Required")]
    public int Quantity { get; set; }
}

View:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>New Inventory Item</h4>
        <hr />
        <div class="form-group">
           <label for="ItemId", class = "control-label col-md-2">Item Id</label>
            <div class="col-md-10">
                <input type="text" value="@Model.ItemId" id="ItemId" readonly />
            </div>
        </div>
    ....
    ....
John Saunders
  • 157,405
  • 24
  • 229
  • 388
abalter
  • 7,589
  • 12
  • 75
  • 118
  • is Model != null? How are you sending model to client? – Claudio Redi Jun 05 '15 at 19:11
  • Wait a second!!! This is the "Create" method. Of course the Model=null until the form is submitted. The controls are blank. It doesn't make any sense to try to display the ItemId before it is created! – abalter Jun 05 '15 at 19:49
  • Then you nailed it :) – Claudio Redi Jun 05 '15 at 19:59
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jun 05 '15 at 20:22

0 Answers0