Click here to Skip to main content
15,885,633 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to list all items in a page developed in asp.net mvc with pagedlist. it is done. I want to update all or selected items. can be listed and can select only selected items but can not post the model to controller. after Update button I can post model but not with values, it is empty.can anyone help?

My code is here.
Debt.cs

SQL
namespace Management.Data.Financial
{
    public enum CurrencyType
    {
        TL = 1
    }
    //TODO: DebtTypes enumu daha sonra tablodan yönetilecek.
    public enum DebtTypes
    {
        Income = 1
    }
    public enum YesNoTypes
    {
        Yes= 1,
        No = 2
    }
    public enum PaymentTypes
    {
        Paid = 1,
        NotPaid = 2,
        NotAllPaid = 3
    }
    public class Debt
    {
        //public bool Selected { get; set; }
        public int Id { get; set; }

        
        public string DebtTerm { get; set; }

        public DebtTypes DebtType { get; set; }
        
        public decimal DebtAmount { get; set; }
       
        public CurrencyType DebtCurrency { get; set; }

        public YesNoTypes DebtIsFixture { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  
        public DateTime DebtDueDate { get; set; }
        
        public PaymentTypes DebtIsPaid { get; set; }
        public decimal DebtRemainAmount { get; set; }

        public DateTime RecordDate { get; set; }
        public string UserId { get; set; }
        public virtual Partition DebtPart { get; set; }
    }
}


My Models

SQL
namespace Management.Models
{

    public class SelectDebtEditorViewModel
    {
        public bool Selected { get; set; }

        public int Id { get; set; }


        public string DebtTerm { get; set; }

        public DebtTypes DebtType { get; set; }

        public decimal DebtAmount { get; set; }

        public CurrencyType DebtCurrency { get; set; }

        public YesNoTypes DebtIsFixture { get; set; }


        public DateTime DebtDueDate { get; set; }

        public PaymentTypes DebtIsPaid { get; set; }
        public decimal DebtRemainAmount { get; set; }

        public DateTime RecordDate { get; set; }
        public string UserId { get; set; }
        public virtual Partition DebtPart { get; set; }
    }

    public class DebtSelectionViewModel
    {
        public List<SelectDebtEditorViewModel> Debt { get; set; }
        public DebtSelectionViewModel()
        {
            this.Debt = new List<SelectDebtEditorViewModel>();
        }

        public IEnumerable<int> getSelectedIds()
        {
            
            return (from d in this.Debt where d.Selected select d.Id).ToList();
        }
    }
   
}


My controller


SQL
namespace Management.Controllers
{


        public ActionResult ListDebts(string sortOrder, string currentFilter, 
            string searchString, string Part,string Term, string PayStat, int? page, bool? checkboxes)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.PartSortList = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DueDateSortList = sortOrder == "Date" ? "date_desc" : "Date";
            ViewBag.AmountSortList = sortOrder == "Amount" ? "amount_desc" : "Amount";
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var debts = from d in db.Debts
                           select d;
            if (!String.IsNullOrEmpty(searchString))
            {
                debts = debts.Where(d => d.DebtPart.PartitionName.Equals(searchString));
            }
            if (!String.IsNullOrEmpty(Part))
            {
                debts = debts.Where(d => d.DebtPart.PartitionName.Equals(Part));
                ViewBag.CurrentFilter = Part;
            }
            if (!String.IsNullOrEmpty(Term))
            {
                debts = debts.Where(d => d.DebtTerm.Equals(Term));
                ViewBag.CurrentFilter = Term;
            }

            switch (sortOrder)
            {
                case "name_desc":
                    debts = debts.OrderByDescending(d => d.DebtPart.PartitionName);
                    break;
                case "Date":
                    debts = debts.OrderBy(d => d.DebtDueDate);
                    break;
                case "date_desc":
                    debts = debts.OrderByDescending(d => d.DebtDueDate);
                    break;
                case "Amount":
                    debts = debts.OrderBy(d => d.DebtAmount);
                    break;
                case "amount_desc":
                    debts = debts.OrderByDescending(d => d.DebtAmount);
                    break;
                default:  // Name ascending 
                    debts= debts.OrderBy(d=>d.DebtDueDate);
                    break;
            }

            List<SelectDebtEditorViewModel> model = new List<SelectDebtEditorViewModel>();

            foreach (var item in debts)
            {
                var editorViewModel = new SelectDebtEditorViewModel()
                {
                    Id = item.Id,
                    DebtPart = item.DebtPart,
                    DebtIsFixture = item.DebtIsFixture,
                    DebtTerm = item.DebtTerm,
                    DebtAmount = item.DebtAmount,
                    DebtDueDate = item.DebtDueDate,
                    DebtIsPaid = item.DebtIsPaid,
                    Selected = false
                };
                model.Add(editorViewModel);
            }
            
            int pageSize = 20;
            int pageNumber = (page ?? 1);
            return View(model.ToPagedList(pageNumber, pageSize));
        }

        public ActionResult Aaa(SelectDebtEditorViewModel model)
        {
            if (model != null)
            {
                return Json("Success");
            }
            else
            {
                return Json("An Error Has occoured");
            }


        }

}


My view

HTML
@model PagedList.IPagedList<Management.Models.SelectDebtEditorViewModel>
           @using PagedList.Mvc;

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

<h2>Income List</h2>
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@section scripts{
    <style type="text/css">
        
        input[type="text"] {
            width: 150px;
        }
    </style>


@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">

    var arr = [];

    function toggleChecked(status) {
        $("#checkboxes input").each(function () {
            $(this).prop("checked", status);
            checkboxcontrol(status);
        });
    }

    $(document).ready(function () {
        $("#checkall").prop('checked', false);
        $("#checkall").click(function () {
            var status = $("#checkall").prop('checked');
            toggleChecked(status);
        });
    });

    function checkboxcontrol(status) {

        var itemValue = $(this).attr("value");
        if (status) {
            arr.push(status);
        }
        else {
            arr.shift();
        }
    }


    $("#checkboxes input").change(function () {       
        if ($(this).is(":checked")) {      
            checkboxcontrol(true);      
        }
        else {        
            checkboxcontrol(false);          
        }       
    });
    
    $("#btnUpdate").click(function (event) {
        if (arr.length<=0) {
            alert("No record selected.");
            event.preventDefault();
            return;
        }
        if (!confirm("You will update are you sure?")) {

            event.preventDefault();
            return;
        }

        var jsonObj = $("#frame").serialize();

        $.ajax({
            url: "@Url.Action("Aaa")",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(jsonObj),
            dataType: "json",
            type: "post",
            error: function (response) {
                alert(response.responseText);
            },
            success: function (response) {
                alert(response);
            }
        });
        callAjax(arr.join(","));
    });
</script>
}

@using (Html.BeginForm("ListDebts", "Financial", FormMethod.Get, new { @class = "form-horizontal", encType = "multipart/form-data", role = "form", id = "frame" , name="frame"}))
{
    @Html.AntiForgeryToken()
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.Label("Part No : ", new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBox("Part", ViewBag.CurrentFilter as string, new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        @Html.Label("Income Term: ", new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBox("Term", ViewBag.CurrentFilter as string, new { @class = "form-control" })
        </div>
    </div>
    
    <div class="form-group">
        @Html.Label("Pay Status : ", new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBox("PayStat", ViewBag.CurrentFilter as string, new { @class = "form-control" })
        </div>
    </div>
        
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="List" />
        </div>
    </div>
    <div>
        <input type="checkbox" id="checkall" /><span>  Select All</span>
    </div>

    <div id="checkboxes">
    <table class="table" id="table">
        <tr>
            <th>
                Seç
            </th>
            <th>
                @Html.ActionLink("Part", "ListDebts", new { sortOrder = ViewBag.PartSortList, currentFilter = ViewBag.CurrentFilter })
            </th>
            <th>
                Fixture
            </th>
            <th>
                Income term
            </th>
            <th>
                @Html.ActionLink("Amount", "ListDebts", new { sortOrder = ViewBag.AmountSortList, currentFilter = ViewBag.CurrentFilter })
            </th>
            <th>
                @Html.ActionLink("Due Date", "ListDebts", new { sortOrder = ViewBag.DueDateSortList, currentFilter = ViewBag.CurrentFilter })
            </th>
            <th>
                PAY Status
            </th>
            <th></th>
        </tr>
      
        @foreach (var item in Model)
        {
            <tr>
                <td style="text-align:center">
                    @Html.CheckBoxFor(modelItem => item.Selected)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DebtPart.PartitionName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DebtIsFixture)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DebtTerm)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DebtAmount) TL
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DebtDueDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DebtIsPaid)
                </td>
                <td>
                    @Html.HiddenFor(modelItem => item.Id)
                </td>
            </tr>
        }
    </table>

        
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-default" value="Update"
                       id="btnUpdate" />

            </div>
        </div>
</div>
<hr />
<br />
}

Sayfa @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) / @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("ListDebts",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900