2012-08-01 63 views
0

我想在MVC应用程序中使用类似于Exit sub的动作,我使用的是c#语言。如何在MVC中退出函数?

当我只输入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); 
    } 
+0

如果sResult!=“Accept”,你想要什么?这是否意味着验证失败?如果它是真的,那么你需要向ModelState添加错误消息并返回View(位置)。 – 2012-08-01 14:17:19

回答

0

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

1

如果我理解你在你的方法做,你可以试试:

[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); 
} 

顺便说一句,有很多地方在这个方法来重构。