简体   繁体   中英

Getting “Value Cannot be Null” when selecting elements from XML

So i have an MVC program that sends information from View form to an XML file. Now this information writes correctly but a break is caused each time due to the following error and i cant understand why!

在此输入图像描述

above is my constructor within ScorecardRepository.cs and the following is my code for my model, namely Scorecard.cs

public partial class Scorecard
{
    public int ScorecardID { get; set; }
    public int VendorID { get; set; }
    public string Title { get; set; }
    public bool Enabled { get; set; }
    public System.DateTime Created { get; set; }
    public int CreatedBy { get; set; }
    public Nullable<System.DateTime> LastUpdated { get; set; }
    public Nullable<int> UpdatedBy { get; set; }

    public Scorecard()
    {
        this.ScorecardID = 0;
        this.VendorID = 0;
        this.Title = null;
        this.Enabled = true;
        this.Created = DateTime.Now;
        this.CreatedBy = 0;
        this.LastUpdated = DateTime.Now;
        this.UpdatedBy = 0;
    }

    public Scorecard(int scorecardid, int vendorid, string title, bool enabled, DateTime created, int createdby, DateTime lastupdated, int updatedby)
    {
        this.ScorecardID = scorecardid;
        this.VendorID = vendorid;
        this.Title = title;
        this.Enabled = enabled;
        this.Created = created;
        this.CreatedBy = createdby;
        this.LastUpdated = lastupdated;
        this.UpdatedBy = updatedby;
    }
}

and here is a sample of my XML file in which the data is written to!

在此输入图像描述

Can anyone help me? My value cannot be null??

One of your item elements does not contain all elements you're looking for.

The exception you're getting is thrown when you're trying cast (XElement)null to non-nullable value type, like int or DateTime :

XElement t = null;
int v = (int)t;

Possible solutions? Change your properties to Nullable<T> or make sure element you're trying to cast to value type do exist in your XML document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM