Ссылка на объект не указывает на экземпляр объекта в модели представления

Я получаю эту ошибку:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error: 
Line 251:            ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);
Line 252:
Line 253:            Currencies = new SelectList(
Line 254:            ManageCurrency.Instance.getCurrencies(), "id", "name",_Account.currency1.id);
Line 255:

Это дает ошибку в этой модели представления

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Common;
using Business;
using System.Web.Mvc;
using System.Web.Security;
using System.Runtime.Remoting.Contexts;

namespace internetBankingApplication.ViewModel
{

    public class NewFixedAccountViewModel
    {
        private account _Account { get; set; }

        private fixedAccount _FixedAccount { get; set; }



        public SelectList AccountTypes { get; set; }

        public SelectList Durations { get; set; }

        public SelectList AccountFromList { get; set; }

        public SelectList Currencies { get; set; }

        public int ID
        {
            get
            {
                return _Account.accountID;
            }
        }

        [Required]
        [Display(Name = "Account Name")]
        public string Name
        {
            get
            {
                return _Account.name;
            }
            set
            {
                _Account.name = value;
            }
        }

        [Required]
        [Display(Name = "Account From")]
        public int accountFrom { get;set;}



        public string AccountFromName
        {
            get
            {
                string result = string.Empty;
                try
                {
                    result = ManageAccount.Instance.GetAccountBYID(accountFrom).name;
                }
                catch { }
                return result;
            }
        }



        [Required]
        [Display(Name = "Duration")]
        public int duration
        {
            get
            {
                return _FixedAccount.duration;
            }
            set
            {
                _FixedAccount.duration = value;
            }
        }

        public string durationName
        {
            get
            {
                string result = string.Empty;
                try
                {
                    result = ManageDuration.Instance.GetDurationById(_FixedAccount.duration).duration1;
                }
                catch { }
                return result;
            }
        }

        [Required]
        [Display(Name = "Available Balance")]
        public decimal AvailableBalance
        {
            get
            {
                return _Account.availableBalance;
            }
            set
            {
                _Account.availableBalance = value;
            }
        }

        [Required]
        [Display(Name = "Currency")]
        public int currency
        {
            get
            {
                return _Account.currency;
            }
            set
            {
                _Account.currency = value;
            }
        }

        public string CurrencyName
        {
            get
            {
                string result = string.Empty;
                try
                {
                    result = ManageCurrency.Instance.getTypesByID(_Account.currency).name;
                }
                catch { }
                return result;
            }
        }


        [Required]
        [Display(Name = "Account Description")]
        public string Description
        {
            get
            {
                return _Account.description;
            }
            set
            {
                _Account.description = value;
            }
        }


        [Required]
        [Display(Name = "Account Renew")]
        public bool renew
        {
            get
            {
                if (_FixedAccount.renew == 0)
                {
                    return false;
                }
                return true;
            }
            set
            {
                if (value == false)
                {
                    _FixedAccount.renew = 0;
                }
                else
                {

                    _FixedAccount.renew = 1;
                }
            }
        }


        public NewFixedAccountViewModel()
        {
           // AccountTypes = new SelectList(
           //ManageAccountType.Instance.getTypes(), "id", "type", _Account.typeID);

            string username = HttpContext.Current.User.Identity.Name.ToString();
            AccountFromList = new SelectList(
            ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);

            **Currencies = new SelectList(
            ManageCurrency.Instance.getCurrencies(), "id", "name",_Account.currency1.id);** //Giving the error

            Durations = new SelectList(
            ManageDuration.Instance.GetAllDurations(), "id", "duration", _FixedAccount.duration);



        }

        public NewFixedAccountViewModel(string username)
        {
            AccountTypes = new SelectList(
            ManageAccountType.Instance.getTypes(), "id", "type", _Account.typeID);


            AccountFromList = new SelectList(
            ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);

            Currencies = new SelectList(
            ManageCurrency.Instance.getCurrencies(), "id", "name", _Account.currency);

            Durations = new SelectList(
            ManageDuration.Instance.GetAllDurations(), "id", "duration", _FixedAccount.duration);


        }

        public NewFixedAccountViewModel(int accountID, string username)
        {
            _Account = ManageAccount.Instance.GetAccountBYID(accountID);

            _FixedAccount = ManageFixedAccount.Instance.GetFixedAccountByID(accountID);

            AccountFromList = new SelectList(
            ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);

            AccountTypes = new SelectList(
            ManageAccountType.Instance.getTypes(), "id", "type", _Account.accountType);

            Currencies = new SelectList(
            ManageCurrency.Instance.getCurrencies(), "id", "name", _Account.currency);

            Durations = new SelectList(
            ManageDuration.Instance.GetAllDurations(), "id", "duration", _FixedAccount.duration);


        }
    }
}

person Anna Marie Rapa    schedule 01.05.2013    source источник


Ответы (2)


Сообщение об ошибке, которое вы получаете, означает, что вы пытаетесь вызвать метод или свойство для нулевого значения, чего вы не можете сделать.

Из того, что я вижу, либо ManageCurrency равно нулю, либо ManageCurrency.Instance равно нулю.

Если ManageCurrency имеет значение null, вызов свойства Instance завершится ошибкой, поскольку нулевые объекты не имеют методов или свойств. Точно так же, если ManageCurrency.Instance равно null, вызов метода getCurrencies завершается ошибкой по той же причине.

В любом случае - это не так сложно отладить. Как предлагает Скумар, установите точку останова в этой строке, запустите в режиме отладки и посмотрите, где находится нулевое значение, а затем вернитесь назад, чтобы выяснить, почему значение равно нулю.

person StanK    schedule 02.05.2013

Имя пользователя, которое вы передаете в следующем коде, может быть пустым или недействительным. Вот почему он возвращает NULL, и возникает вышеуказанное исключение.

AccountFromList = new SelectList(
            ManageAccount.Instance.GetUserAccounts(username), "accountID", "name", accountFrom);
person Santosh Panda    schedule 01.05.2013
comment
нет я проверял.. работает нормально.. проблема в валютах - person Anna Marie Rapa; 01.05.2013
comment
Поставьте точку останова в строке валют и запустите программу в режиме ОТЛАДКИ. После того, как он достигнет точки останова, проверьте соответствующие объекты, если какой-либо объект является NULL или нет. - person Santosh Panda; 01.05.2013