0

I'm trying to figure out how to work with ASP.NET route system so I've decided to develop the application which would allow the administrator to manage students and groups they're in. I'm not going into developing the database because right now my goal is to decide how to configure routes.

Right now I'm using the following system:

I've added Groups controller to view and edit groups. I'll provide only the parts of code that work with groups and students omitting models since IMHO they're not important.

So, when you enter the Groups controller Index page, the Index method is executed:

public ActionResult Index()
    {
        var groups = groupManager.GetGroups();
        return View(groups);
    }

Groups are displayed as follows:

@foreach (var item in Model) 
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Title)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.Id }) |
        @Html.ActionLink("Manage students", "Index", "Students", new { id = item.Id }, null)
    </td>
</tr>
}

Students controller has a static variable to hold the group you're working with:

public static int currentGroupId;

When you click the 'Manage students' link, the Students controller's Index method is executed and the current id of the group you've chosen is passed:

public ActionResult Index(int? id)
    {
        Group group = groupManager.FindById(id);
        currentGroupId = id.Value;
        return View(studentManager.GetStudentsByGroup(id));
    }

When you edit/create/delete the student, this id is used to redirect you back to Student's controller Index or to attach the student to the group as follows:

public ActionResult Create([Bind(Include = "Id,Title,Group")] Student student)
    {
        if (ModelState.IsValid)
        {
            student.Group = groupManager.FindById(currentGroupId);
            studentManager.Add(student);
            return RedirectToAction("Index/" + currentGroupId);
        }
        return View(student);
    }

The same approach is used inside the edit view if you want to return to the list of students:

@Html.ActionLink("Back to List", "Index/" + StudentsController.currentGroupId)

It works fine but I'm not really sure that it's okay. I strongly dislike the usage of static variable inside the controller and I also don't like the way it looks in the address bar; you have something like 'localhost/Students/Index/{groupId}' when you view the students but you have 'localhost/Students/Edit/{studId}' when you edit the student which doesn't seem nice for me since the routes don't seem logical and understandable.

I've tried to set up a route using attributes. I've created the following routes for Students contoller in another project (in this example there's no page to edit groups, you enter the students page just from the corresponding group page):

public class StudentsController : Controller
{
    [Route("Groups/Group/{id}/Students")]
    public ActionResult Index(int? id)
    {
        return View();           
    }

    [Route("Students/{studId?}")]
    public ActionResult Student(int? studId)
    {
        return View();
    }

    [Route("Students/{studId}/Edit")]
    public string Edit(int studId)
    {
        return "Editing " + studId;
    }
}

[Route("Groups/Group/{id}/Students")] - this route is used to display the list of students in the group.

[Route("Students/{studId?}")] - this route is used to display the information about the user.

[Route("Students/{studId}/Edit")] - this route is used to edit the chosen user.

The routes work fine when I want to jump from one link to another but I wasn't able to figure out how to get the Group id when I want to create the student. The route doesn't contain it and I don't have any variable to hold it.

Could anybody recommend some smooth way to implement this functionality without using a static variable? Perhaps I should use another route, say, 'Groups/Group/{groupId}/Students/{studId}/Edit' so that I will be able to get the groupId from route?

Update:

As I've already understood, static is a real fail but I don't know how to store the information about the group. It's used everywhere in controller. I think I can try to save it inside the Html.ActionLink as route parameter. However, it'll get a bit complicated since I'll have to pass the value again whenever I have to write another method.

Update 2

I've finally managed to solve the problem, albeit not in the best way. I've used the routing attributes to set up the path. I've decided to use the path like 'Groups/Group/{groupId}/{Students}' because I need the groupId to go back to Index from edit/create/delete student pages.

So here's how it looks now:

First, I've changed the link to the manage students page. The link is displayed on groups Index page near each group.

@Html.ActionLink("Manage students", "Index", "Students", new { groupId = item.Id }, null)

Then I've changed the student Index method:

    [Route("Groups/Group/{groupId}/Students")]
    public ActionResult Index(int groupId)
    {
        ViewBag.groupId = groupId; //To use it in the view
        return View(studentManager.GetStudentsByGroup(groupId));
    }

The Index view contains groupId to use it in the 'go back to Index' link inside edit/create/delete pages:

        <td>
            @Html.ActionLink("Edit", "Edit", new { groupId = ViewBag.groupId, studentId = item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { groupId = ViewBag.groupId, studentId = item.Id })
        </td>

The edit methods look as follows:

   [Route("Groups/Group/{groupId}/Students/Edit/{Id}")]
    public ActionResult Edit(int groupId, int? studentId)
    {
        Student student = studentManager.FindById(studentId);
        return View(student);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Route("Groups/Group/{groupId}/Students/Edit/{Id}")]
    public ActionResult Edit([Bind(Include = "Id,Name")] Student student)
    {
        if (ModelState.IsValid)
        {
            var studentWithId = studentManager.FindById(student.Id); 
            var groupId = studentWithId.Group.Id; //Because we don't pass the groupId to the Edit; should fix it ASAP
            var group = groupManager.FindById(groupId);
            student.Group= group;
            studentManager.Edit(student);
            return RedirectToAction("Index", new { groupId = groupId }); //To display the list of the student for that group when you finish editing
        }
        return View(student);
    }

And here's the usage of 'back to list' link. ViewBag isn't used because already have the id in model.

@Html.ActionLink("Back to List", "Index", new {groupId = Model.Group.Id })

I suppose this way is better than the static variable but I don't like passing the groupId from view to controller and back whenever I have to do something. I don't think ViewData or TempData will work here since I have to let a user edit different groups at the same time and if I call TempData["groupId"] = groupId when they click the manage students button, it'll be absolutely the same as with the static variable. I guess I'll leave it as it is for now, maybe I'll come up with something better later.

6
  • What happens when one user is managing a group with ID = 1 then another user then begins to manage a group with ID = 2. The first user saves, but it saves to group with ID = 2 (because the static variable has been updated by the second user). Don't use static variables!
    – user3559349
    Nov 11, 2014 at 21:50
  • Why not just use the default route? If you name your controllers and action methods as you'd like them in the url, there is no need for the complexity of custom routes. Also I don't see the purpose of the static variable. There is no problem sending values to the methods either individually or via a view model. Keep it simple!
    – Kirby
    Nov 12, 2014 at 0:51
  • @Stephen Yeah, I had a feeling that that was a bad decision but unfortunately I wasn't able to test the scenario you mentioned and nor did I think of it when I was reviewing the code. My mistake. Nov 12, 2014 at 1:02
  • 1
    I'm not sure why you think the default routes don't seem logical and understandable. Students/Index for all students, Students/Details/1 to view details of student with ID=1, Students/Edit/1 to edit details of student with ID=1 all make sense to me. If you don't like Students/Index/1 to display students with GroupID=1, then add a method say public ActionResult Group(int ID) so it can be Students/Group/1
    – user3559349
    Nov 12, 2014 at 1:10
  • @Kirby I've updated the post to give more information since the restraint on comments doesn't allow me to write a lot here. Nov 12, 2014 at 1:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.