Asp.net Can';创建列表时,不要从控制器返回视图
这是我遇到的问题的简化版本。基本上,VisualStudio不允许我在控制器内创建对象(如列表)Asp.net Can';创建列表时,不要从控制器返回视图,asp.net,asp.net-mvc,asp.net-mvc-4,Asp.net,Asp.net Mvc,Asp.net Mvc 4,这是我遇到的问题的简化版本。基本上,VisualStudio不允许我在控制器内创建对象(如列表) using System.Collections.Generic; using System.Web.Mvc; namespace HDDTest0818.Controllers { public class HomeController : Controller { public ViewResult Index() { p
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();
}
}
}
使用System.Collections.Generic;
使用System.Web.Mvc;
命名空间HDDTest0818.Controllers
{
公共类HomeController:控制器
{
公共视图结果索引()
{
public List someList=新列表();
返回视图();
}
}
}
以下是我得到的错误:
Index
-HomeController.Index();:并非所有代码路径都返回值
第三个大括号-}应为
return
-类、结构或接口成员声明中的无效标记“return”
视图
-“HomeController.View”必须声明一个主体,因为它没有标记为抽象、外部或部分
View
-'HomeController.View'隐藏继承的成员'Controller.View'。如果打算隐藏,请使用新关键字
视图
-方法必须具有返回类型
最后一个结束大括号-
类型或命名空间定义,或预期的文件结尾
您需要修改代码:
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();
}
}
}
使用System.Collections.Generic;
使用System.Web.Mvc;
命名空间HDDTest0818.Controllers
{
公共类HomeController:控制器
{
//在这里,您可以将列表变量声明为public,以便该变量的作用域可以在整个类中。。。
//public List someList=新列表();
公共视图结果索引()
{
/*public*/List someList=new List();
//在创建列表变量之前,需要去掉public
//如果要将此列表变量声明为公共变量,则需要在方法(Index())之外执行此操作。。
返回视图();
}
}
}
让我知道这是否有帮助 这些都是编译时错误,您的c代码无效。
public List someList=new List()代码>->List someList=newlist()代码>啊,谢谢蚂蚁P!成功了!为什么它不能是公共的呢?因为它是方法内部的局部变量,而不是类级字段。使用public
没有意义。在创建列表变量之前,不需要public