问题描述
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()
中的 HomeController
方法没有返回值。查看 Index()
方法,我发现缺少 return 语句。向 Index()
方法添加 return 语句以消除此错误。用以下方法替换您的索引方法。这是您方法的精确副本,但最后一条语句 View();
替换为 return View();
。
[HttpGet]
public IActionResult Index() // the Index is underline in red
{
ViewBag.Fifteen = 0;
ViewBag.Twenty = 0;
ViewBag.TwentyFive = 0;
return View();
}