grisdof
grisdof

Reputation: 21

How to send Data from Controller to cshtml with ASP.NET Core 3.0

I am working with a own dataBase where i want to get descriptions out of my DB and put the data into a table in html. But i can't really find anything useful and i don't really know how to transmit the data from the controller to the view - or how to request the data from the view to the Controller.

This is how my Controller looks like:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Test.Models;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult getTableNames()
        {
            DatabaseItemDescription databaseItemDescription = new DatabaseItemDescription();
            databaseItemDescription.Name = "abc";
            databaseItemDescription.Description = "def";
            databaseItemDescription.Content = "ghi";

            return View(databaseItemDescription); //Does this work?
        }
    }
}

This is how my Index.cshtml looks like:

@page
@model DatabaseItemDescription

<h1>DatabaseEditTest</h1>


<table id="buttonTable">
    <thead>

    </thead>
</table>

<table id="descriptionTable"
       class="table table-bordered table-condensed table-striped">
    <thead>
        <tr>
            <th>Action</th>
            <th>Name</th>
            <th>Description</th>
            <th>Content</th>
        </tr>
    </thead>

    <tbody>

    </tbody>
</table>


<script>
    function getFirstTableDesc() {
        $("#firstTable thead").remove();
        $("#buttonTable thead").append("<tr>" + "<th><button onclick='updateTableDesc()'>Update</button></td>" + "<th><button onclick='refreshTableDesc()'>Refresh</button></td>" + "<tr>");
    }

    function updateTableDesc() {
        $("#descriptionTable tbody").empty();

        //here i want to read the Data from the Controller and insert it into the table like:
        //Fetch Data from Controller
        //$("#descriptionTable tbody").append("<tr>" + "<td><button onclick='Edit()'>Edit</button></td>" + "<td>${Name}</td>" + "<td>${Description}</td>" + "<td>${Content}</td>" + "</tr>");
    }
    }

    function refreshTableDesc() {

    }
</script>

I would be really thankful if somebody could help me! Thank you

Upvotes: 1

Views: 2451

Answers (4)

Rahul Sharma
Rahul Sharma

Reputation: 8312

Okay, so regarding your case there is a very good plugin called DataTables that you can use to show your data on your View from the Controller. You can refer to the below code snippet for your requirement:

Your Model:

namespace Test.Models
{
    public class DatabaseItemDescription 
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string Content { get; set; }
    }
}

Your Controller:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Test.Models;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public JsonResult getTableNames()
        {
            List<DatabaseItemDescription> databaseItemDescription = new List<DatabaseItemDescription>();

            //Example of how you could initialize your list
            databaseItemDescription.Add(new DatabaseItemDescription
            {
             Name = "abc",
             Description = "def",
             Content = "ghi"
            });

            databaseItemDescription.Add(new DatabaseItemDescription
            {
             Name = "efg",
             Description = "hij",
             Content = "klm"
            });

            return Json(databaseItemDescription, JsonRequestBehavior.AllowGet);
        }
    }
}

And your View would look like:

@{
    ViewBag.Title = "Home Page";
    Layout = null;
}

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    @*<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
        <script src="~/Scripts/jquery-3.4.1.js"></script>
        <link href="~/Content/bootstrap4.min.css" rel="stylesheet" />
        <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
        <script src="~/Scripts/DataTables/dataTables.bootstrap4.min.js"></script>*@

    <!-- CDN LINKS-->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.3.1/cerulean/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
    <div class="jumbotron">
        <h1>DataTable Example</h1>
        <p class="lead">A project dedicated to data table example in MVC</p>
    </div>
    <br />
    <center>
        <div style="width: auto; border: 1px solid black; padding: 3px" ;>
            <table id="dataTable">
                <thead>
                    <tr>
                        <th style="width: auto; border: 1px solid black; padding: 3px" ;>Name</th>
                        <th style="width: auto; border: 1px solid black; padding: 3px" ;>Description </th>
                        <th style="width: auto; border: 1px solid black; padding: 3px" ;>Content </th>
                    </tr>
                </thead>
            </table>
        </div>
    </center>
    <script type="text/javascript">
            $(document).ready(function () {
                $.ajax({
                    "url": "@Url.Action("getTableNames", "Home")",
                    "method": "post",
                    "dataType" : "json",
                    success: function (data) {
                        $('#dataTable').DataTable({
                            paging: true,
                            sort: true,
                            searching: true,
                            data:data,
                            columns: [
                                { 'data': 'Name'},
                                { 'data': 'Description' },
                                { 'data': 'Content' }
                            ]
                        });
                    }
                });
            });
    </script>
</body>
</html>

For your refreshing and update, you can refer to the official documentation of the plugin or you can create your custom buttons and bind them using AJAX to your Controller methods. I hope this helps you out.

Upvotes: 0

Mukesh Modhvadiya
Mukesh Modhvadiya

Reputation: 2178

You have mixed the things, there are two approach you can change and make it work, if you want your view to change as @Felipe Oriani has suggested, you also need to change your Index method and return data from it as model

    public IActionResult Index()
    {
        DatabaseItemDescription databaseItemDescription = new DatabaseItemDescription();
        //prepare model

        return View(databaseItemDescription);
    }

then you can bind using @Modal.Name, @Model.Description etc.

Other approach as you tried to get data from JS as below, get data using Ajax call and bind response

function updateTableDesc() {
    //here i want to read the Data from the Controller and insert it into the table like:
    //Get data using Ajax call to "Home/getTableNames" and bind using JS
}

And change your getTableNames method to return Json

    public IActionResult getTableNames()
    {
        DatabaseItemDescription databaseItemDescription = new DatabaseItemDescription();
        //prepare model
        return Json(databaseItemDescription); //this will work
    }

Upvotes: 0

Felipe Oriani
Felipe Oriani

Reputation: 38608

Given you have a strongly-typed view in the code (with @model woth m in lowercase),

@model DatabaseItemDescription

You can use the Model property in a view to read information that comes from Controller.

return View(databaseItemDescription); //Does this work?

You are passing this object which is the type of DatabaseItemDescription to your View as a Model. You can access this information my Model, so, you can try this:

<tr>
    <th> Maybe you add some links here to perform actions like edit/delete </th>
    <th>@Model.Name</th>
    <th>@Model.Description</th>
    <th>@Model.Content</th>
</tr>

It is just to read information from what is comming from controller and display it on the view. You can add more properties if you need.

Upvotes: 1

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

Try this:

<tr>
    <th>@Model.Action</th>
    <th>@Model.Name</th>
    <th>@Model.Description</th>
    <th>@Model.Content</th>
</tr>

Upvotes: 0

Related Questions