创建列表时无法从控制器返回视图

时间:2016-08-18 18:30:01

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

这是我遇到的问题的简化版本。基本上,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

1 个答案:

答案 0 :(得分: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();
        }
    }
}

请告诉我这是否有帮助!