如何在MVC中退出函数



我想在MVC应用程序中使用类似Exit sub的操作,我正在使用c#语言。

当我只键入return时,它显示一个错误。它要求强制性ActionResult

    [HttpPost]
    public ActionResult Create(Location location)
    {
        if (ModelState.IsValid)
        {
            Validations v = new Validations();
            Boolean ValidProperties = true;
            EmptyResult er;
            string sResult = v.Validate100CharLength(location.Name, location.Name);
            if (sResult == "Accept")
            {
                ValidProperties = true;
            }
            else
            {
    //What should I write here ? 
    //I wan to write return boolean prperty false 
            // When I write return it asks for the ActionResult
            }
             if (ValidProperties == true)
             {
                 db.Locations.Add(location);
                 db.SaveChanges();
                 return RedirectToAction("Index");
             }
        }
        ViewBag.OwnerId = new SelectList(
                            db.Employees, "Id", "FirstName", location.OwnerId);
        return View(location);
    }

如果我理解你在方法中做了什么,你可以试试:

[HttpPost]
public ActionResult Create(Location location)
{
    if (ModelState.IsValid)
    {
        Validations v = new Validations();
        Boolean ValidProperties = true;
        EmptyResult er;
        string sResult = v.Validate100CharLength(location.Name, location.Name);
        if (sResult == "Accept")
        {
            ValidProperties = true;
        }
        else
        {
            ValidProperties = false;
            ModelState.AddModelError("", "sResult is not accepted! Validation failed");
        }
         if (ValidProperties == true)
         {
             db.Locations.Add(location);
             db.SaveChanges();
             return RedirectToAction("Index");
         }
    }
    ViewBag.OwnerId = new SelectList(
                        db.Employees, "Id", "FirstName", location.OwnerId);
    return View(location);
}

顺便说一句,在这种方法中有很多重构的地方。

如果一个方法被声明为返回void以外的任何类型,则不能使用返回指令退出它,并且必须提供返回类型。返回null通常是答案。然而,在MVC中,您可能希望返回一些内容,向用户指示出现了问题。

最新更新