c# - 我不知道如何使用 C# 修复 ASP.NET MVC 中的这个 cs0161 错误
问题描述
我不断收到此错误,我不知道如何解决它:
CS0161:Home.Controller.Index():并非所有代码路径都返回值
using Microsoft.AspNetCore.Mvc;
using TipCalculator.Models;
namespace TipCalculator.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index() // the Index is underline in red
{
ViewBag.Fifteen = 0;
ViewBag.Twenty = 0;
ViewBag.TwentyFive = 0;
View();
}
[HttpPost]
public IActionResult Index(Calculator calc)
{
if (ModelState.IsValid)
{
ViewBag.Fifteen = calc.CalculateTip(0.15);
ViewBag.Twenty = calc.CalculateTip(0.20);
ViewBag.TwentyFive = calc.CalculateTip(0.25);
}
else
{
ViewBag.Fifteen = 0;
ViewBag.Twenty = 0;
ViewBag.TwentyFive = 0;
}
return View(calc);
}
}
}
解决方案
**CS0161:Home.Controller.Index():并非所有代码路径都返回值
帮助您理解此消息。上面的错误消息意味着Index()
方法 inHomeController
不返回值。查看Index()
方法,我看到缺少 return 语句。向方法添加 return 语句Index()
以消除此错误。用以下方法替换您的索引方法。这是您的方法的精确副本,但最后一条语句View();
替换为return View();
.
[HttpGet]
public IActionResult Index() // the Index is underline in red
{
ViewBag.Fifteen = 0;
ViewBag.Twenty = 0;
ViewBag.TwentyFive = 0;
return View();
}
推荐阅读
- command - 将目录和文件移动到父目录
- python - Groupby 客户的 id 并保留 Pandas 中不为空的日期
- java - 如何让java中的线程休眠几毫秒?
- php - PHP 检查数组中的特定值是否为真
- sql - 与 cte union all select
- amazon-web-services - 登录 AWS STS 登录
- pytorch - 如何从 CUDA 11.4 降级到 10.2 并添加 sm_35 - CUDA 错误:没有可在设备上执行的内核映像
- java - 如何删除给定 PDF 中的“TEST”,然后使用任何 Java 库保存它
- typescript - TS:断言对象的非空属性
- reactjs - Eslint 抱怨绝对进口