C# InvalidOperationException Web应用程序
我不太熟悉它的工作原理,但我正在尝试提交并计算输入的存款或取款金额,但现在我遇到了以下错误:InvalidOperationException:Nullable对象必须有一个值 我觉得我需要一双新的眼睛来观察这件事,因为我的精神被卡住了 BankAppModel.cs:C# InvalidOperationException Web应用程序,c#,html,asp.net-core,C#,Html,Asp.net Core,我不太熟悉它的工作原理,但我正在尝试提交并计算输入的存款或取款金额,但现在我遇到了以下错误:InvalidOperationException:Nullable对象必须有一个值 我觉得我需要一双新的眼睛来观察这件事,因为我的精神被卡住了 BankAppModel.cs: using System.ComponentModel.DataAnnotations; namespace Proj1BankApp.Models { public class BankAppModel {
using System.ComponentModel.DataAnnotations;
namespace Proj1BankApp.Models
{
public class BankAppModel
{
[Required(ErrorMessage = "Please enter a name.")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a transaction month.")]
public string TransactionMonth { get; set; }
[Required(ErrorMessage = "Please enter a transaction day.")]
[Range(1, 31, ErrorMessage = "The transaction day must be between 1 and 31.")]
public int TransactionDay { get; set; }
[Required(ErrorMessage = "Please enter a transaction year.")]
public int TransactionYear { get; set; }
public decimal? Balance { get; set; }
public decimal? WithdrawAmount { get; set; }
public decimal? DepositAmount { get; set; }
public decimal Deposit()
{
decimal balance = 0;
balance = Balance.Value + DepositAmount.Value;
return balance;
}
public decimal Withdraw()
{
decimal balance = 0;
if(Balance.Value < WithdrawAmount.Value)
{
return balance;
}
else
{
balance = balance - WithdrawAmount.Value;
return balance;
}
}
}
}
在调用其value属性之前,请确保您的可空字段具有值。我假设在您的
存款
方法中有余额
或存款金额
空值。尝试将断点放在那个里,并检查这些属性是否分配了空值
或者您可以添加空检查,如(在draw
方法中以相同的方式):
using Microsoft.AspNetCore.Mvc;
using Proj1BankApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Proj1BankApp.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
ViewBag.BankApp = "";
return View();
}
[HttpPost]
public IActionResult Index(BankAppModel obj, string submit)
{
if (ModelState.IsValid)
{
ViewBag.BankApp = obj.Deposit().ToString("c2");
ViewBag.BankApp = obj.Withdraw().ToString("c2");
}
else
{
ViewBag.BankApp = "";
}
return View();
}
}
}
public decimal Deposit()
{
decimal balance = 0;
if(Balance.HasValue && DepositAmount.HasValue)
{
balance = Balance.Value + DepositAmount.Value;
}
return balance;
}