需要显示学生表的必填字段

时间:2017-02-13 11:04:24

标签: c# asp.net-mvc

我是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);
        }
    }
}

2 个答案:

答案 0 :(得分: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,因为这是默认情况下在路由配置中设置的。

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