简体   繁体   中英

(Edit/5) not working but (edit?id=5) working in MVC 5

I just started learning MVC and I was trying to pass studentId as a parameter to an edit page. By default, when you click on the Edit link, it goes to:

 localhost:63348/student/Edit/5 

but it doesn't work. it gives me this error

The parameters dictionary contains a null entry for parameter 'StudentId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'WebApplication1.Controllers.StudentController'.`

But if I change it manually to:

 localhost:63348/student/Edit?studentid=5

it then works. Should they mean the same thing and work almost the same way?

Here's my controller:

public IList<Student>studentList = new List<Student>{
            new Student() { StudentId = 1, StudentName = "John", Age = 18 } ,
            new Student() { StudentId = 2, StudentName = "Steve",  Age = 21 } ,
            new Student() { StudentId = 3, StudentName = "Bill",  Age = 25 } ,
            new Student() { StudentId = 4, StudentName = "Ram" , Age = 20 } ,
            new Student() { StudentId = 5, StudentName = "Ron" , Age = 31 } ,
            new Student() { StudentId = 6, StudentName = "Chris" , Age = 17 } ,
            new Student() { StudentId = 7, StudentName = "Rob" , Age = 19 }
        };

    [Route("Edit/{studentId:int")]
    public ActionResult Edit(int StudentId)
    {
        //Get the student from studentList sample collection 
        var std = studentList.Where(s => s.StudentId == StudentId).FirstOrDefault();

        return View(std);
    }

Tried adding a specific route config but didn't work either:

routes.MapRoute(
            name: "StudentEdit",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Student", action = "Edit", id = UrlParameter.Optional }
        );

You need to add attribute [FromUri] and correct the compiling issues (Provide closing bracket } and the argument name is not same.

[Route("Edit/{studentId:int}")]
    public ActionResult Edit([FromUri] int studentId)
    {
        //Get the student from studentList sample collection 
        var std = studentList.Where(s => s.StudentId == StudentId).FirstOrDefault();

        return View(std);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM