【问题标题】:Not all code paths return a value in Controller并非所有代码路径都在 Controller 中返回值
【发布时间】:2017-01-26 23:50:58
【问题描述】:

我似乎无法弄清楚为什么我的 [HttpPost]Index() 方法给了我一条错误消息,指出

并非所有代码路径都返回值

我尝试将return View() 放在AddModelError 之后,但它仍然给我该错误消息。

public class SnowboardController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(SnowboardModel SbModel)
    {
        if (SbModel.DiscountSenior && SbModel.DiscountStudent)
        {
            ModelState.AddModelError("Discounts", "Dude, you cannot take both student and senior discounts.");
        }
        //return to view if any fields invalid
        if (!ModelState.IsValid)
        {
            return View(SbModel);
        }
    }
}

在我的视图中我还添加了@Html.ValidationMessage("Discounts")

【问题讨论】:

  • 因为没有return 语句如果你们都没有if 条件返回false 通常你会在方法的底部保存和重定向代码(return RedirectToAction(...);)跨度>

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


【解决方案1】:

在 Index 方法中,你所有的返回值都被包裹在 ifs 中……你需要在方法结束时返回一个。

【讨论】:

    猜你喜欢
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2013-10-06
    • 2016-02-14
    • 2014-04-02
    相关资源
    最近更新 更多