Search code examples
c#asp.netasp.net-mvcactionlink

ASP.NET MVC, Actionlink


I am revisiting MVC after some time I am facing some weird errors, which I just can't seem to solve.

@Model List<StockEdgeTest.Models.Department>
@using StockEdgeTest.Models

@{
    ViewBag.Title = "Department List";
}

<div style="font-family:'Agency FB'">
    <h2>Department List</h2>

    <ul>
        @foreach (Department dep in @Model)
        {
            <li>
                @Html.ActionLink(dep.DepartmentName, "Index", "Employee", new { DepartmentID = Convert.ToInt32(dep.DepartmentID) })
            </li> 
        }

    </ul>
</div>

This View gives o/p

System.Collections.Generic.List`1[StockEdgeTest.Models.Department] List Department List HR Finance DB IT Management Corpo Bank Facilities Useless Directors

I do not know how to remove this line System.Collections.Generic.List`1[StockEdgeTest.Models.Department] List

More importantly, the actionlink does not seem to working, it just generates https://localhost:44354/?Length=8 instead of https://localhost:44354/Employee/Index

any ideas how to address this? EDIT: action

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StockEdgeTest.Models;

namespace StockEdgeTest.Controllers
{
    public class DepartmentController : Controller
    {
        // GET: Department
        public ActionResult Index()
        {
            EmployeeContext ecn = new EmployeeContext();
            List<Department> e1 = ecn.Department.ToList();
            return View(e1);
        }

    }
}

Solution

  • fix your view :

    @model List<StockEdgeTest.Models.Department>
    
    @{
        ViewBag.Title = "Department List";
    }
    
    <div style="font-family:'Agency FB'">
        <h2>Department List</h2>
    
        <ul>
            @foreach (Department dep in @Model)
            {
                <li>
    @Html.ActionLink(dep.DepartmentName, "Index", "Employee", new { id = dep.DepartmentID}, null )
                </li> 
            }
    
        </ul>
    </di
    
    

    and in you Index action replace:

    return View()
    

    with

    [Route("{id?}")]
    public ActionResult Index(int id)
    {
        .....
    List<StockEdgeTest.Models.Department> model= ...your code
    return view(model);
    }
    ```