首页 > 解决方案 > 我不知道如何使用 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);
        }
    }
}

标签: c#asp.netasp.net-mvc

解决方案


**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();
}

推荐阅读