Search code examples
javascriptasp.net-mvcactionlink

How to Pass id value of actionlink to javascript function in my Asp.net Mvc Project


I have a table for departments. Right now I created controller for every department and every department have index.cshtml. But they use the same functions. I hard coded their departmentId in every index page. for example for department IT with departmentId = 1

public class ItController : Controller
    {
        // GET: It
        public ActionResult Index()
        {
            return View();
        }
    }

And in It's index page I have hard coded with decleration var id = 1; Like this

<div class="panel panel-body">

<div class="col-md-4 table-responsive" id="productsTable"></div>
</div>

 <script type="text/javascript">

var id = 1; // for the department that id is 1 so I have to create index for every department and hard code like this


 function AllProductsByDepartmentId(id) {

            var tbl = $('#productsTable');
            $.ajax({
                cache: false,
                url: '/Home/GetAllProductsByDepartmentId?id=' + id,
                contentType: 'application/html ; charset:utf-8',
                type: 'GET',
                dataType: 'html',
                success: function (result) {
                    tbl.empty().append(result);
                },
                error: function () {

                }

            });

        }

</script>

But to do like this is not good becouse if by some reasen changes Id of department or when I create a new department next time then I have to hard coded again ... What I want is first I want to populate those departments in my _Layout dynamicaly from database. So I created controller

    public class DepartmentsController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Departments
        public async Task<ActionResult> Index()
        {
            return View(await db.Departments.ToListAsync());
        }
    }

And this is my PartialView of Departments and I want to populate it in _Layout.cshtml, but I don't know how to do and how to link them to a function ...

@model IEnumerable<Inventory.Models.Departments>
@foreach (var item in Model) {
     @Html.ActionLink(modelItem => item.DepartmentName???????, ??????, ?????, new { id = item.DepartmentId })

  }

and link them to this java function

function AllProductsByDepartmentId(id)
{
   // ......
}

I think I have to create another common controller to have an index page to all departments.But How to create actionlinks dynamicaly and link them to javascript function. Thank you in advance!


Solution

  • There is no need to use @Html.ActionLink() to generate links in this case. You foreach loop can be just

    @foreach (var item in Model) {
        <a href="#" class="details" data-id="@item.DepartmentId">@item.DepartmentName</a>
    }
    

    Note that the value of DepartmentId is added to the link as a data attribute.

    Then you script would be

    var url = '@Url.Action("GetAllProductsByDepartmentId", "Home")';
    var tbl = $('#productsTable');
    $('.details').click(function() {
        tbl.load(url, { id: $(this).data('id') });
    });