如何解决异常错误? [英] How to solve an exception error?
本文介绍了如何解决异常错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的控制器上面有上面的代码,
i have a above code on my controller,
public ActionResult Details(int? id)
{
var dbo = new DrugBusiness();
DrugModel dm = dbo.DetailsMethod(id);
DateTime drug_expdate = dbo.GetAll().Find(x => x.DrugId == id).ExpiryDate;
DateTime now = DateTime.Today;
var days = drug_expdate - now;
if(drug_expdate<=now)
{
ViewBag.msg = "The Drug has expired";
}
else
{
ViewBag.msg = "This Drug expires in " + days.Days + "Days";
}
return PartialView(dbo.DetailsMethod(id));
但是当我运行我的详细信息视图时,它给出了一个黄色的错误,这就是
but when im running my Details view it's giving me an error in yellow line, this what
it says "{"Object reference not set to an instance of an object."}"
请帮我试试但是什么都没有用,请
please help me ive try but nothing is working, please
推荐答案
你可能会注意到问号在int?
之后。这意味着id也可以为NULL,因此您必须检查它。
You might notice the questionmark afterint?
. This means that id can also be NULL so you have to check for that.
if(id.HasValue) {
// do something
} else {
// id is NULL, do something else
}
祝你好运!
Good luck!
你通过的身份证可能不是在记录中找到。因此,无法访问ExpiryDate。要么没有这样的id,要么你为id提供了一个空值。
您是否可以将可空的内容传递给方法。基于代码看起来它不是为处理这样的输入而设计的。
Probably the id you're passing cannot be found in records. Because of this, the ExpiryDate cannot be accessed. Either there is no such id or you have provided a null value for the id.
Is it intentional that you can pass a nullable into to the method. Based on the code it looks like it's not designed to handle such input.
在执行任何计算之前检查drug_expdate的值是否为空。
Check to see if the value for "drug_expdate is not null before performing any calculations.
DateTime drug_expdate = dbo.GetAll().Find(x => x.DrugId == id).ExpiryDate;
DateTime now = DateTime.Today;
if (drug_expdate != null)
{
var days = drug_expdate - now;
}
这篇关于如何解决异常错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文