Send (Pass) dynamic column values to Controller on Button Click using AngularJS in ASP.Net MVC

mahesh213
 
on Dec 01, 2020 10:27 PM
Sample_741663.zip
1246 Views

Hi,

How to push values from view to controller after clicking of save button

Dynamically add columns and set value using AngularJS in ASP.Net MVC

After clicking of save button how to push it's values to controller

I need to save values in database like below format

ItemDate

Id   ItemId    Date           Price

1      1         02/11/2020     10

2      2         03/11/2020       3

3      2         04/11/2020       7

4      1         05/11/2020       8

where Id - primary key 

Could you please help me

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 02, 2020 06:45 AM
on Dec 03, 2020 11:11 PM

Hi mahesh213,

Check the code.

Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult GetData()
    {
        List<Item> itemLists = new List<Item>();
        itemLists.Add(new Item { ItemId = 1, ItemName = "a" });
        itemLists.Add(new Item { ItemId = 2, ItemName = "b" });

        List<ItemDate> itemDates = new List<ItemDate>();
        itemDates.Add(new ItemDate { Id = 1, ItemId = 1, Date = Convert.ToDateTime("02/11/2020"), Price = 10 });
        itemDates.Add(new ItemDate { Id = 1, ItemId = 1, Date = Convert.ToDateTime("06/11/2020"), Price = 8 });
        itemDates.Add(new ItemDate { Id = 1, ItemId = 2, Date = Convert.ToDateTime("04/11/2020"), Price = 1 });
        itemDates.Add(new ItemDate { Id = 1, ItemId = 1, Date = Convert.ToDateTime("08/11/2020"), Price = 5 });

        DateTime? Fdate = itemDates.Min(x => x.Date);
        DateTime? tdate = itemDates.Max(x => x.Date);

        List<ItemEntryDetail> itemEntryDetails = new List<ItemEntryDetail>();
        for (int row = 0; row < itemLists.Count; row++)
        {
            List<DatePrice> dt = new List<DatePrice>();

            for (DateTime? i = Fdate; i <= tdate; i = i.Value.AddDays(1))
            {
                dt.Add(new DatePrice { Date = i.Value.ToString("dd-MM-yyyy") });
            }

            ItemEntryDetail itemEntryDetail = new ItemEntryDetail();
            itemEntryDetail.Id = itemLists[row].ItemId;
            itemEntryDetail.Item = itemLists[row].ItemName;

            for (int column = 0; column < dt.Count; column++)
            {
                ItemDate itemDate = itemDates.Where(x => x.ItemId == itemLists[row].ItemId && x.Date == Convert.ToDateTime(dt[column].Date)).FirstOrDefault();

                dt[column].Price = itemDate != null ? itemDate.Price.ToString() : "";
                itemEntryDetail.Dates = dt;
            }
            itemEntryDetails.Add(itemEntryDetail);
        }

        return Json(itemEntryDetails, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public ActionResult SaveData(List<ItemEntryDetail> data)
    {
        // Loop through the data and insert in database.
        return View();
    }

    public class Item
    {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
    }

    public class ItemDate
    {
        public int Id { get; set; }
        public int ItemId { get; set; }
        public DateTime Date { get; set; }
        public int Price { get; set; }
    }

    public class ItemEntryDetail
    {
        public int Id { get; set; }
        public string Item { get; set; }
        public List<DatePrice> Dates { get; set; }
    }

    public class DatePrice
    {
        public string Date { get; set; }
        public string Price { get; set; }
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller('MyController', function ($scope, $window, $http) {
            $.post("/Home/GetData/", function (r) {
                $scope.items = r;
                $scope.columns = r[0].Dates.length;
                $scope.$apply();
            });
            $scope.Save = function () {
                var data = [];
                for (var i = 2; i < $('#tblDetails tr').length; i++) {
                    var obj = {};
                    obj.Item = $('#tblDetails tr').eq(i).find('td').eq(1).html();
                    var detail = [];
                    for (var j = 0; j < $scope.columns; j++) {
                        var date = $('#tblDetails tr').eq(1).find('td').eq(j + 2).html();
                        var price = $('#tblDetails tr').eq(i).find('td').eq(j + 2).find('input').val();
                        detail.push({ 'Date': date, 'Price': price });
                    }
                    obj.Dates = detail;
                    data.push(obj);
                }
                // Send to Controller.
                $http({
                    method: "Post",
                    url: "/Home/SaveData",
                    dataType: 'json',
                    headers: { "Content-Type": "application/json" },
                    data: '{data: ' + JSON.stringify(data) + '}'
                });
            };
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <div class="container" id="printarea">
        <table id="tblDetails" class="table table-bordered">
            <tr class="success">
                <th>Id</th>
                <th>Item</th>
                <th colspan="{{columns}}" class="text-center">Date</th>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td ng-repeat="i in items[0].Dates">{{i.Date}}</td>
            </tr>
            <tr ng-repeat="item in items">
                <td>{{item.Id}}</td>
                <td>{{item.Item}}</td>
                <td ng-repeat="i in item.Dates">
                    <input type="text" ng-model="i.Price" style="width: 100px" />
                </td>
            </tr>
        </table>
    </div>
    <input type="button" value="Save" ng-click="Save()" />
</body>
</html>

Screenshots

Values in Form

Values in Controller