获取错误:并非所有代码路径都返回值
我是mvc C#的新手,我被卡住了。 请告知如何解决这个问题。 我在Add上收到错误。 当我将鼠标hover在红色波浪线上时,它会显示“并非所有代码路径都返回值”
public ActionResult Add(ShapeInputModel dto, FormCollection collection) { var model = new GeoRegions(); if (TryUpdateModel(model)) { var destinationFolder = Server.MapPath("/App_Data/KML"); var postedFile = dto.Shape; if (postedFile != null) { var fileName = Path.GetFileName(postedFile.FileName); var path = Path.Combine(destinationFolder, fileName); postedFile.SaveAs(path); //Save to Database Db.AddGeoRegions(model); return RedirectToAction("Index"); } return View(); } }
用这个 :
public ActionResult Add(ShapeInputModel dto, FormCollection collection) { var model = new GeoRegions(); if (TryUpdateModel(model)) { var destinationFolder = Server.MapPath("/App_Data/KML"); var postedFile = dto.Shape; if (postedFile != null) { var fileName = Path.GetFileName(postedFile.FileName); var path = Path.Combine(destinationFolder, fileName); postedFile.SaveAs(path); //Save to Database Db.AddGeoRegions(model); return RedirectToAction("Index"); } return View(); } return null; // you can change the null to anything else also. }
发生错误是因为如果TryUpdateModel(model) = false
您的函数不会返回任何内容。 所以添加行return null
或return 'any other thing'
将解决问题!
如果从未输入“if”,则无法return
。
我喜欢始终保持if-else的[使用return]平衡,我可以一目了然地看到返回值(并且所有路径都有返回值):
if (TryUpdateModel(model)) { ... if (postedFile != null) { ... return RedirectToAction("Index"); } else { return View(); } } else { return View(); // or null/whatever is appropriate }
当然ReSharper经常告诉我,我有“无用”的其他陈述;-)
快乐的编码。
加
return null;
在最后一行之前}
如果(TryUpdateModel(model))
返回false
(TryUpdateModel(model))
返回任何内容。 也许你打算让你的return View();
在if
之外?
错误就像它在锡上说的那样; 有一个代码路径,函数将完成,但不会返回值。 具有返回类型的函数必须始终返回值或抛出exception。
在您的情况下,如果TryUpdateModel(model)
返回false
,则您没有返回值。
好好看看错误! 在方法执行的某个时刻,您必须返回一个值,或抛出exception。 (我认为在这种情况下返回null是有序的)
当然,你的初始if (TryUpdateModel(model))
使你的例程只在条件为true
时返回一个值; 如果不是,则不会返回任何内容,这违反了方法签名。
你有
if (TryUpdateModel(model)) { // lots of stuff return View(); }
那么,如果TryUpdateModel
不正确,将返回什么?
即使if
语句为false,您的方法也必须返回ActionResult
。
只需快速查看代码,我就可以看到你有返回命令(在“if”语句块中返回View()。现在如果“If”条件失败,则在其范围之外没有return语句。最简单的方法是
} return View(); } return null; // Depends upon your code though. you might want to return something else }
您在“if()”条件中返回值。 如果条件失败,会发生什么? 该计划将不会返回价值。 因此,如果条件,则返回任何默认值,它可能处于其他条件。
public ActionResult Add(ShapeInputModel dto, FormCollection collection) { var model = new GeoRegions(); if (TryUpdateModel(model)) { .... .... } return default_value;//it may be in else condition also. }
试试吧。 如果你的问题得到解决,那么标记为已回答。 这对其他人有用。