2017-02-13 65 views
-1

我是C#的新手我已经将学生列表发送给模型。但是当我在路由中输入值时,我也只需要指定的列表来显示。需要显示学生表的必填字段

这是我的控制器:

using System.Web.Mvc; 
using Project1.Models; 

namespace Project1.Controllers 
{ 
    public class StudentController : Controller 
    { 

     public ActionResult Index() 
     { 
      var studentList = new List<Student> 
      { 
       new Student() { StudentId = 1, Studentname = "aa", Age = 18 } , 
       new Student() { StudentId = 2, Studentname = "bbb", Age = 21 }   
      }; 

      return View(studentList); 
     } 
    } 
} 
+0

问题是什么? –

+0

您应该首先阅读教程,或者更优选先阅读有关C#的书籍(因为您说自己是初学者),然后介绍ASP.NET MVC。只是在没有正确理解的情况下跳入随机主题,在编程世界中毫无意义。 –

+0

我需要访问指定的列表示例,如果我给... ..../1在url中,我只需要只显示studentid1 –

回答

1

你应该一个int id参数添加到Index行动然后将集合筛选为

public ActionResult Index(int id) 
{ 
    var studentList = new List<Student> 
    { 
     new Student() { StudentId = 1, Studentname = "aa", Age = 18 } , 
     new Student() { StudentId = 2, Studentname = "bbb", Age = 21 } 
    }; 

    return View(studentList.Where(s => s.StudentId == id)); 
} 

该参数的名称确实重要,我写了id,因为这是默认情况下在路由配置中设置的。

+0

我geting作为服务器错误'/'在应用程序 –

+0

什么是确切的错误信息? –

0

你已经默认索引方法。你需要重载。

您的基本方法:

public ActionResult Index() 
{ 
    var studentList = new List<Student> 
    { 
     new Student() { StudentId = 1, Studentname = "aa", Age = 18 }, 
     new Student() { StudentId = 2, Studentname = "bbb", Age = 21 } 
    }; 
    return View(studentList); 
} 

而且其超载

public ActionResult Index(int id) 
{ 
    var studentList = new List<Student> 
    { 
     new Student() { StudentId = 1, Studentname = "aa", Age = 18 }, 
     new Student() { StudentId = 2, Studentname = "bbb", Age = 21 } 
    }; 
    return View(studentList.Where(filter => filter.StudentId == id)); 
} 

你的类的最终情况会是这样:

public class StudentController : Controller 
{ 
    public ActionResult Index() 
    { 
     var studentList = new List<Student>{ new Student() { StudentId = 1, Studentname = "aa", Age = 18 } , new Student() { StudentId = 2, Studentname = "bbb", Age = 21 } }; 
     return View(studentList); 
    } 

    public ActionResult Index(int id) 
    { 
     var studentList = new List<Student> 
     { 
      new Student() { StudentId = 1, Studentname = "aa", Age = 18 }, 
      new Student() { StudentId = 2, Studentname = "bbb", Age = 21 } 
     }; 
     return View(studentList.Where(filter => filter.StudentId == id)); 
    } 
} 
+0

你应该在这里指出与路由有关的问题,即默认参数名称是'id',所以没有任何东西会被绑定到'filter',除非他做了正确的配置。 –

+0

你说得对。我编辑过它。旧习惯。通常我不会在我自己的项目中使用默认参数。 –