gpt4 book ai didi

asp.net - MVC中返回View时为"Not all code paths return a value"

转载 作者:行者123 更新时间:2023-12-02 13:35:40 25 4
gpt4 key购买 nike

如果对象(国家/地区)不为空,我想返回一个 View 。但我收到错误“并非所有代码路径都返回值”

我的代码如下

public ActionResult Show(int id)
{
if (id != null)
{
var CountryId = new SqlParameter("@CountryId", id);
Country country = MyRepository.Get<Country>("Select * from country where CountryId=@CountryId", CountryId);
if (country != null)
{
return View(country);
}
}

}

最佳答案

当您从“if”语句中返回某些内容时,就会发生这种情况。编译器会想,如果“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 CountryId=@CountryId", CountryId);

if (country != null)
{
return View(country);
}
else
{
return View(something);
}
}
else
{
return View(something);
}
}

关于asp.net - MVC中返回View时为"Not all code paths return a value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36824838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com