2016-08-18 60 views
1

这是我遇到的问题的简化版本。基本上,Visual Studio不会让我在控制器内部创建一个对象(如列表)。创建列表时无法从控制器返回视图

using System.Collections.Generic; 
using System.Web.Mvc; 

namespace HDDTest0818.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ViewResult Index() 
     { 
      public List<string> someList = new List<string>(); 

      return View(); 
     } 
    } 
} 

下面是我得到的错误:

Index - HomeController.Index();: not all code paths return a value

第三个开括号 - } expected

return - Invalid token 'return' in class, struct, or interface member declaration

View - 'HomeController.View' must declare a body because it is not marked abstract, extern, or partial

View - 'HomeController.View' hides inherited member 'Controller.View'. Use the new keyword if hiding was intended

View - Method must have a return type

最后收花括号 - Type or namespace definition, or end-of-file expected

+0

这些都是编译时错误,你有无效的C#代码。 – Louis

+1

'public List someList = new List ();' - >'List someList = new List ();' –

+0

啊,谢谢你蚂蚁P!这工作!为什么不能公开呢? –

回答

2

你需要修改你的代码:

using System.Collections.Generic; 
using System.Web.Mvc; 

namespace HDDTest0818.Controllers 
{ 
    public class HomeController : Controller 
    { 
     //here is where you would declare your List variable public so that scope of this variable can be within the entire class... 
     // public List<string> someList = new List<string>(); 
     public ViewResult Index() 
     { 
      /*public*/ List<string> someList = new List<string>(); 
      //you need to get rid of public before you create your List variable 
      // if you want to declare this list variable as public you need to do it outside of the method (Index()).. 

      return View(); 
     } 
    } 
} 

让我知道,如果这有助于!

+0

这非常有帮助!谢谢!!! –

+1

@TaylorLiss不客气。很高兴我能帮上忙! –

相关问题