当MVC中返回视图时,“不是所有的代码路径都返回一个值”
问题描述:
我想在对象(国家/地区)不为空时返回视图。但我得到的错误“并非所有的代码路径返回一个值”当MVC中返回视图时,“不是所有的代码路径都返回一个值”
我的代码看起来像这样
public ActionResult Show(int id)
{
if (id != null)
{
var CountryId = new SqlParameter("@CountryId", id);
Country country = MyRepository.Get<Country>("Select * from country where [email protected]", CountryId);
if (country != null)
{
return View(country);
}
}
}
答
当您返回从“如果”语句中的东西会出现这种情况。编译器认为,如果“if”条件是错误的呢?这样,即使在函数中定义了返回类型“ActionResult”时,也不会返回任何内容。因此,在else语句中添加一些默认返回值:
public ActionResult Show(int id)
{
if (id != null)
{
var CountryId = new SqlParameter("@CountryId", id);
Country country = MyRepository.Get<Country>("Select * from country where [email protected]", CountryId);
if (country != null)
{
return View(country);
}
else
{
return View(something);
}
}
else
{
return View(something);
}
}