Paging In MVC Table Grid - c#

What I am trying to achieve is to include paging functionality in a grid (generated with an html table and a foreach statement).
I am not allowed to use entity framework, webgrid, or any other third party grid.
Below are the details of my task:
DemoTestData.cs file
namespace Demo.Data
{
public class DemoTestData
{
DemoTestModel objdemoTestModel = null;
public string connectionString { get; set; }
public SqlConnection objConnection { get; set; }
public SqlCommand objCommand { get; set; }
public SqlDataReader objReader { get; set; }
public List<DemoTestModel> GetAllDemoTest()
{
List<DemoTestModel> listDemoTest = new List<DemoTestModel>();
try
{
objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
objConnection.Open();
objCommand = new SqlCommand("sp_DemoTest", objConnection);
objCommand.CommandType = System.Data.CommandType.StoredProcedure;
objReader = objCommand.ExecuteReader();
if (objReader.HasRows)
{
while (objReader.Read())
{
// list will be populated here.
objdemoTestModel = new DemoTestModel();
objdemoTestModel.Id = Convert.ToInt32(objReader["Id"].ToString());
objdemoTestModel.Column1 = objReader["Column1"].ToString();
objdemoTestModel.Column2 = objReader["Column2"].ToString();
objdemoTestModel.Column3 = objReader["Column3"].ToString();
objdemoTestModel.Column4 = objReader["Column4"].ToString();
objdemoTestModel.Column5 = objReader["Column5"].ToString();
objdemoTestModel.Column6 = objReader["Column6"].ToString();
listDemoTest.Add(objdemoTestModel);
}
//return listStateModel;
}
}
catch (Exception ex)
{
string m = ex.Message;
}
finally
{
if (objConnection != null)
{
objConnection.Close();
}
}
return listDemoTest;
}
}
}
sp_DemoTest procedure
CREATE PROCEDURE [dbo].[sp_DemoTest]
AS
BEGIN
select Id,Column1,Column2,Column3,Column4,Column5,Column6 from dbo.DemoTest
END
DemoTestModel.cs file
namespace Demo.Entities
{
public class DemoTestModel
{
public int Id { get; set; }
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
public string Column4 { get; set; }
public string Column5 { get; set; }
public string Column6 { get; set; }
}
}
DemoTestController.cs file
namespace SampleProject.Controllers
{
public class DemoTestController : Controller
{
// GET: /DemoTest/
//Test tst = new Test();
DemoTestData data = new DemoTestData();
//List<CountryModel> ListModel = new List<CountryModel>();
List<DemoTestModel> ListModel = new List<DemoTestModel>();
//DemoTestModel demoTestModel = new DemoTestModel();
public ActionResult Index()
{
ListModel = data.GetAllDemoTest();
return View(ListModel);
}
}
}
Index.cshtml file
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Column1)
</th>
<th>
#Html.DisplayNameFor(model => model.Column2)
</th>
<th>
#Html.DisplayNameFor(model => model.Column3)
</th>
<th>
#Html.DisplayNameFor(model => model.Column4)
</th>
<th>
#Html.DisplayNameFor(model => model.Column5)
</th>
<th>
#Html.DisplayNameFor(model => model.Column6)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#if (item.Column1 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column1)
}
else if (item.Column1 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column1, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column1)
}
</td>
<td>
#if (item.Column2 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column2)
}
else if (item.Column2 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column2, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column2)
}
<td>
#if (item.Column3 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column3)
}
else if (item.Column3 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column3, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column3)
}
</td>
<td>
#if (item.Column4 == "Textbox")
{
#Html.TextBox("test", "", new { style = "width:130px;" })
}
else if (item.Column4 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column4, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column4)
}
</td>
<td>
#if (item.Column5 == "Textbox")
{
#Html.TextBox("test1", "", new { style = "width:130px;" })
}
else if (item.Column5 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column5, Enumerable.Empty<SelectListItem>(), new { style = "width: 130px" })
}
else
{
#Html.DisplayFor(modelItem => item.Column5)
}
</td>
<td>
#if (item.Column6 == "Textbox")
{
#Html.TextBoxFor(modelItem => item.Column6)
}
else if (item.Column6 == "Dropdown")
{
#Html.DropDownListFor(modelItem => item.Column6, Enumerable.Empty<SelectListItem>())
}
else
{
#Html.DisplayFor(modelItem => item.Column6)
}
</td>
</tr>
}
</table>
(if..else condition is used to generate dynamic controls)
This is the rendered view
It would be very nice if anyone could provide a solution.

Related

Why does 'InvokeAsync' show as an error in a Blazor component?

I've recently started including Blazor components in my ASP.Net core web app. I've decided to split my components into multiple files using the pattern [ComponentName].razor and [ComponentName].razor.cs for all the C# coding.
Something annoying which has been popping up is all my state change notification calls are showing as errors. Now, these errors disappear when I build and run the app, but they still congest my error list window. These will disappear if I close and then open Visual Studio 2019, but they come back after a couple of minutes. What is going on and how can I fix these errors?
Cheers!
InvokeAsync highlighted as an error
Edit: Here's some code as requested. The offending lines are in TransactionTableView.razor.cs. 'await InvokeAsync(StateHasChanged)' shows up as an error.
TransactionTableView.razor
<table class="table data-table" id="taskstable">
<thead>
<tr>
#if (ShowSelect)
{
<th>
<input type="checkbox" #bind="SelectAllTransactions" #bind:event="oninput" #onclick="() => CheckAllTransactions(!SelectAllTransactions)"/>
Select all
</th>
}
#if (ShowParent)
{
<th>
Parent
</th>
}
<th>
Task
</th>
<th>
Status
</th>
<th>
Due Date
</th>
<th>
Completion Date
</th>
<th>
Amount Due
</th>
<th>
Amount Paid
</th>
<th>
Comments
</th>
</tr>
</thead>
<tbody class="tasks-body">
#if (Transactions != null)
{
#foreach (var transaction in DisplayTransactions)
{
<tr class="#transaction.AlertClassDisplay()">
#if (ShowSelect)
{
<td>
<input #bind="transaction.Select" type="checkbox" #oninput="() => SelectSingleTask(transaction.TransactionId)"/>
</td>
}
#if (ShowParent)
{
<td>
#transaction.TenementKey
</td>
}
<td>
#transaction.Description
</td>
<td class="task-status">
<a asp-action="Details" asp-controller="Alerts" method="get" asp-route-transactionId="#transaction.TransactionId">
#transaction.TransactionStatus
</a>
</td>
<td>
#transaction.DueDateDisplay()
</td>
<td>
#($"{transaction.CompletionDate:dd MMM yyyy}")
</td>
<td>
#transaction.AmountDue
</td>
<td>
#transaction.AmountPaid
</td>
<td>
#transaction.Comments
</td>
</tr>
}
}
</tbody>
</table>
TransactionTableView.razor.cs
partial class TransactionTableView
{
// Injected services
[Inject]
private ApplicationDbContext _context { get; set; }
// Data
public List<int> TenementIds { get; set; }
public List<TransactionViewModel> Transactions { get; set; }
public List<TransactionViewModel> DisplayTransactions { get; set; }
public List<Filter> Filters { get; set; } = new List<Filter>();
private bool ShowParent { get; set; } = true;
private bool ShowSelect { get; set; } = true;
private bool SelectAllTransactions { get; set; } = false;
public async Task Refresh()
{
var transactions = new List<Transaction>(_context.Transactions.Where(x => x.TenementId != null && TenementIds.Contains((int)x.TenementId)));
transactions = transactions.OrderBy(x => x.DueDate).ToList();
var models = new List<TransactionViewModel>();
transactions.ForEach(x =>
{
models.Add(x.GetViewModel(_context));
});
Transactions = models;
await RefreshFilters();
}
public async Task RefreshFilters()
{
var holder = Transactions;
if (Filters != null)
{
foreach (var filter in Filters)
{
if(filter.FilteringProperty.PropertyType == typeof(string))
{
holder = holder.Where(x => ((string)filter.FilteringProperty.GetValue(x)).ToLower().Contains(filter.Values.First().ToString().ToLower())).ToList();
}
if(filter.FilteringProperty.PropertyType == typeof(DateTime) || filter.FilteringProperty.PropertyType == (typeof(DateTime?)))
{
var dFilter = (DateFilter)filter;
if (dFilter.SelectedAfterDate)
{
holder = holder.Where(x => (DateTime)dFilter.FilteringProperty.GetValue(x) > dFilter.TargetDate).ToList();
}
else if (dFilter.SelectBeforeDate)
{
holder = holder.Where(x => (DateTime)dFilter.FilteringProperty.GetValue(x) < dFilter.TargetDate).ToList();
}
else if (dFilter.SelectBetweenDates)
{
holder = holder.Where(x =>
{
var targetDate = (DateTime)dFilter.FilteringProperty.GetValue(x);
return targetDate < dFilter.TargetDate && targetDate > (DateTime)dFilter.FirstTargetDate;
}).ToList();
}
}
if(filter.FilteringProperty.PropertyType == typeof(TransactionStatus))
{
var targetStatuses = filter.Values.Select(x => (TransactionStatus)x);
holder = holder.Where(x => targetStatuses.Contains(x.TransactionStatus)).ToList();
}
}
}
DisplayTransactions = holder;
await RefreshAllTaskSelector();
await InvokeAsync(StateHasChanged);
}
private async Task CheckAllTransactions(bool checkAll)
{
foreach(var displayTask in DisplayTransactions)
{
displayTask.Select = checkAll;
}
await InvokeAsync(StateHasChanged);
}
private async Task SelectSingleTask(int transactionId)
{
var task = DisplayTransactions.SingleOrDefault(x => x.TransactionId == transactionId);
task.Select = !task.Select;
if (DisplayTransactions.Any() && DisplayTransactions.Where(x => !x.Select).Count() == 0)
{
SelectAllTransactions = true;
}
else
{
SelectAllTransactions = false;
}
await InvokeAsync(StateHasChanged);
}
private async Task RefreshAllTaskSelector()
{
if (DisplayTransactions.Any() && DisplayTransactions.Where(x => !x.Select).Count() == 0)
{
SelectAllTransactions = true;
}
else
{
SelectAllTransactions = false;
}
}
private async Task DeleteSelected()
{
if (_context.ChangeTracker.HasChanges())
{
throw new ApplicationException("DB already has changes");
}
var targets = new List<TransactionViewModel>(DisplayTransactions.Where(x => x.Select));
foreach(var target in targets)
{
Transactions.Remove(target);
DisplayTransactions.Remove(target);
var transaction = _context.Transactions.SingleOrDefault(x => x.TransactionId == target.TransactionId);
_context.Transactions.Remove(transaction);
}
await _context.SaveChangesAsync();
await InvokeAsync(StateHasChanged);
}
private async Task CompleteSelected()
{
if (_context.ChangeTracker.HasChanges())
{
throw new ApplicationException("DB already has changes");
}
var targets = new List<TransactionViewModel>(DisplayTransactions.Where(x => x.Select));
foreach (var target in targets)
{
var dbTask = _context.Transactions.SingleOrDefault(x => x.TransactionId == target.TransactionId);
dbTask.CompletionDate = DateTime.Now;
dbTask.TransactionStatus = TransactionStatus.Completed;
target.CompletionDate = dbTask.CompletionDate;
target.TransactionStatus = dbTask.TransactionStatus;
var orig = Transactions.SingleOrDefault(x => x.TransactionId == target.TransactionId);
orig.CompletionDate = dbTask.CompletionDate;
orig.TransactionStatus = dbTask.TransactionStatus;
}
await _context.SaveChangesAsync();
await RefreshFilters();
await InvokeAsync(StateHasChanged);
}
private async Task ArchiveSelected()
{
if (_context.ChangeTracker.HasChanges())
{
throw new ApplicationException("DB already has changes");
}
var targets = new List<TransactionViewModel>(DisplayTransactions.Where(x => x.Select));
foreach (var target in targets)
{
var dbTask = _context.Transactions.SingleOrDefault(x => x.TransactionId == target.TransactionId);
dbTask.CompletionDate = DateTime.Now;
dbTask.TransactionStatus = TransactionStatus.Archived;
target.CompletionDate = dbTask.CompletionDate;
target.TransactionStatus = dbTask.TransactionStatus;
var orig = Transactions.SingleOrDefault(x => x.TransactionId == target.TransactionId);
orig.CompletionDate = dbTask.CompletionDate;
orig.TransactionStatus = dbTask.TransactionStatus;
}
await _context.SaveChangesAsync();
await RefreshFilters();
await InvokeAsync(StateHasChanged);
}
}
I've tried with a little test project and I can confirm that you can have 2 possible issue:
you have created/moved the code behind file TransactionTableView.razor.cs in another folder than the TransactionTableView.razor (as said by Henk) without specify the #inherits path
you haven't derived your class from ComponentBase
If you want to separate the two files in two different folder you need to add inherits, like here:
EmployeeData.razor in Pages folder
#page "/employee/{Id}"
#using TestMenu.Shared
#using TestMenu.Client.Services
#inherits TestMenu.Client.Pages.test.EmployeeData
<h3>Employee</h3>
Result data: <b>#employeeData</b>
EmployeeData.razor.cs in Pages/test folder
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using TestMenu.Client.Services;
using TestMenu.Shared;
namespace TestMenu.Client.Pages.test
{
public partial class EmployeeData: ComponentBase
{
[Inject] IEmployeeService EmployeeService { get; set; }
[Parameter]
public string Id { get; set; }
protected Employee Employee = new();
protected string employeeData;
protected override async Task OnInitializedAsync()
{
Employee = (await EmployeeService.GetEmployeeById(int.Parse(Id)));
employeeData = Employee.Name;
await InvokeAsync(StateHasChanged);
}
}
}
if you remove the : ComponentBase from the code behind of EmployeeData.razor.cs, you receive an error like the one in your screenshot.

LINQ Bind in List

i want to bind in list, how to do that, please see my code below
this below is my Controller
var transaction = await (from a in _context.Transaction group a by a.Nobukti into pg
join b in _context.ChartAccount on pg.FirstOrDefault().Kodeakun
equals b.Kodeakun
select new Transaksi
{
Nobukti = pg.FirstOrDefault().Nobukti,
Tanggal = pg.FirstOrDefault().Tanggal,
Keterangan = pg.FirstOrDefault().Keterangan,
Trans = pg.ToList()
}).ToListAsync();
return View(transaction);
See my Trans = pg.ToList() in Controller, inside pg.ToList() there are Kodeakun, and i want bind to Kodeakun = a.Kodeakun + b.Kodeakun
This below is my Model
public class ChartAccount
{
[Key]
public string Kodeakun { get; set; }
public string Namaakun { get; set; }
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal Saldo { get; set; }
}
public class Transaksi
{ [Key]
public int Iud { get; set; }
public int Id { get; set; }
public string Nobukti { get; set; }
public string Kodeakun { get; set; }
public string Keterangan { get; set; }
[DataType(DataType.Date)]
public DateTime Tanggal { get; set; }
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal Debit { get; set; }
[DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = false)]
public decimal Kredit { get; set; }
public virtual List<Transaksi> Trans { get; set; }
}
this below is my view
<table class="table">
#foreach (var item in Model)
{
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Nobukti) :
#Html.DisplayFor(modelItem => item.Nobukti)
</th>
<th>
#Html.DisplayNameFor(model => model.Keterangan) :
#Html.DisplayFor(modelItem => item.Keterangan)
</th>
<th>
#Html.DisplayNameFor(model => model.Tanggal) :
#Html.DisplayFor(modelItem => item.Tanggal)
</th>
</tr>
</thead>
<tbody>
#foreach (var transaksi in item.Trans)
{
<tr>
<td>
#Html.DisplayFor(modelItem => transaksi.Kodeakun)
</td>
<td>
#if (transaksi.Debit == 0) { }
else
{
#Html.DisplayFor(modelItem => transaksi.Debit)
}
</td>
<td>
#if (transaksi.Kredit == 0) { }
else
{
#Html.DisplayFor(modelItem => transaksi.Kredit)
}
</td>
</tr>
}
</tbody>
}
</table>
sorry for my bad english, i use ASP Net Core 2.2

Is there a way to dynamically set model values in a controller?

Model
public class CustomPInfo
{
public List<PSelect> PSelectList { get; set; }
public List<ExcludeItem> ExcludeItemList { get; set; }
public List<customP> CustomPList { get; set; }
}
public class PSelect
{
public string BClass { get; set; }
public int BClassId { get; set; }
public bool Lvl1 { get; set; }
public bool Lvl2 { get; set; }
public bool Lvl3 { get; set; }
public bool Lvl4 { get; set; }
}
public class ExcludeItem
{
public string Item{ get; set;}
public Nullable<int> BClassId { get; set; }
public bool Exclude { get; set; }
}
public partial class customP
{
public int id { get; set; }
public int Lvl {get; set;}
public Nullable<bool> item1 { get; set; }
public Nullable<bool> item2 { get; set; }
public Nullable<bool> item3 { get; set; }
...
public Nullable<bool> item10 { get; set; }
}
Controller
public ActionResult CustomPanel()
{
CustomPInfo customPInfo = new CustomPInfo();
customPanelInfo.PSelectList = new List<PSelect>();
var pSelectList = from p in db.BClass select new
PSelect { BClass = p.BClass, BClassId = p.id };
foreach (var item in pSelectList)
{
customPInfo.PSelectList.Add(item);
}
customPInfo.ExcludeItemList = new List<ExcludeItem>();
var excludeItemList = from p in db.Item.OrderBy(p => p.BClass_id) select new ExcludeItem { Item = p.Name, BClassId = p.BClass_id };
foreach (var item in excludeItemList)
{
customPInfo.ExcludeItemList.Add(item);
}
customPInfo.CustomPList = new List<customP>();
customP customP = new customP();
var i = 1;
do
{
customP.lvl = i;
customPInfo.CustomPList.Add(customP);
++i;
} while (i <= 4);
return View(customPInfo);
}
[HttpPost]
public ActionResult CustomP(CustomPInfo customPInfo)
{
foreach (var X in customPInfo.ExcludeItemList)
{
if (X.Exclude == false)
{
foreach (var item in customPInfo.PSelectList)
{
if (X.BClassId == item.BClassId)
{
foreach (var CustomP in customPInfo.CustomPList)
{
if (CustomP.custom_panel_id == 1 && item.Lvl1 == true)
{
--How can I set the parameter value of CustomP from a variable?
CustomP. item.item = true;
}
if (CustomP.custom_panel_id == 2 && item.Lvl2 == true)
{
CustomP. item.item = true;
}
if (CustomP.custom_panel_id == 3 && item.Lvl3 == true)
{
CustomP. item.item = true;
}
if (CustomP.custom_panel_id == 4 && item.Lvl4 == true)
{
CustomP. item.item = true;
}
}
}
}
}
}
return View();
}
View
#{oldBClassId = 0}
#foreach (var X in Model.ExcludeItemList)
{
foreach (var item in Model.PSelectList)
{
if (X.BClassId == item.BClassId)
{
<tr>
#if (oldBClassId != item.BClassId)
{
<td style="border-top: 1px solid #cdd0d4" align="center">
#Html.CheckBoxFor(modelItem => item.Lvl1, new { id = "CBLVL1" })
</td>
<td style="border-top: 1px solid #cdd0d4" align="center">
#Html.CheckBoxFor(modelItem => item.Lvl2, new { id = "CBLVL2" })
</td>
<td style="border-top: 1px solid #cdd0d4" align="center">
#Html.CheckBoxFor(modelItem => item.Lvl3, new { id = "CBLVL3" })
</td>
<td style="border-top: 1px solid #cdd0d4" align="center">
#Html.CheckBoxFor(modelItem => item.Lvl4, new { id = "CBLVL4" })
</td>
<td style="border-top: 1px solid #cdd0d4">
#Html.DisplayFor(modelItem => item.BClass)
#Html.HiddenFor(modelItem => item.BClassId)
</td>
<td style="border-top: 1px solid #cdd0d4">
#Html.DisplayFor(modelItem => X.item)
#Html.HiddenFor(modelItem => X.ClassId)
</td>
<td style="border-top: 1px solid #cdd0d4" align="center">
#Html.CheckBoxFor(modelItem => X.Exclude)
</td>
{
oldBClassId = item.BClassId;
}
}
else
{
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
#Html.DisplayFor(modelItem => X.item)
#Html.HiddenFor(modelItem => X.BClassId)
</td>
<td align="center">
#Html.CheckBoxFor(modelItem => X.Exclude)
</td>
}
</tr>
}
}
The View is a table of checkboxes that allow someone to select a group of items and exclude a single item of that group.
In the controller is there a way to loop through a list of the item's and be able to update the model properties? This would allow the setting of individual items in 4 customPs from a selected checkbox in the group and exclude individual items in all of the 4 customPs
As str variable is a string , you should access properties of an object with string like this object[string].
foreach (var str in itemList)
{
model[str] = true;
}

C# , MVC , Instead table html

I have this model :
public class CoursesTeacher
{
public int Id { get; set; }
public string FullName { get; set; }
public IEnumerable<string> CourseName { get; set; }
public IEnumerable<int> CourseId { get; set; }
}
I would like to create an Instead table html by razor.
The teacher has a multiple courses.
like that
that
I wrote this code :
<table class="table table-bordered">
<tr>
<th>
#Html.ActionLink("Teacher Name", "RequestsTeachers")
</th>
<th>
#Html.ActionLink("Corese Name", "RequestsTeachers")
</th>
<th>
Edit
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td rowspan="#item.CourseName.Count()">
#Html.DisplayFor(modelItem => item.FullName)
</td>
#foreach (var courseName in item.CourseName)
{
<td>
#Html.DisplayFor(modelItem => courseName)
</td>
}
#foreach (var courseId in item.CourseId)
{
<td>
<div class="pull-right">
#Html.NoEncodeActionLink("<span class='glyphicon glyphicon-pencil'></span>", "Edit", "EditFinancial", "Control", routeValues: new { courseId = courseId }, htmlAttributes: new { data_modal = "", #class = "btn btn-default" })
</div>
</td>
}
</tr>
}
but created not correct :
correct
how to create correct ?
I'd go and create a viewmodel to represent the info for a course:
public class CourseInfoModel
{
public string CourseName { get; set; }
public int CourseId { get; set; }
public bool IsFirstCourse { get; set; }
}
Then in the model class, create a readonly property to get the data in a more suitable way:
public class CoursesTeacher
{
public int Id { get; set; }
public string FullName { get; set; }
public IEnumerable<string> CourseName { get; set; }
public IEnumerable<int> CourseId { get; set; }
public IList<CourseInfoModel> Courses
{
get
{
if (CourseName == null || CourseId == null || CourseId.Count() != CourseName.Count())
throw new Exception("Invalid data"); //courses and ids must have the same number of elements
var list = new List<CourseInfoModel>();
for (int i = 0; i < CourseName.Count(); i++)
{
list.Add(new CourseInfoModel
{
IsFirstCourse = i == 0,
CourseId = CourseId.ElementAt(i),
CourseName = CourseName.ElementAt(i),
});
}
return list;
}
}
}
Now in the view is easy to render the table the way you want:
#model IEnumerable<MvcTable.Models.CoursesTeacher>
<table class="table table-bordered">
<tr>
<th>
#Html.ActionLink("Teacher Name", "RequestsTeachers")
</th>
<th>
#Html.ActionLink("Course Name", "RequestsTeachers")
</th>
<th>
Edit
</th>
</tr>
#foreach (var item in Model)
{
foreach (var courseItem in item.Courses)
{
<tr>
#if (courseItem.IsFirstCourse)
{
<td rowspan="#item.Courses.Count">
#Html.DisplayFor(modelItem => item.FullName)
</td>
}
<td>
#Html.DisplayFor(modelItem => courseItem.CourseName)
</td>
<td>
<div class="pull-right">
<span class='glyphicon glyphicon-pencil'></span>
</div>
</td>
</tr>
}
}
</table>
Instead of keeping the CourseName and CourseIds to seperate lists. Why not create a class to represent a course and use that ?
public class CourseVm
{
public int Id { set; get;}
public string Name { set; get;}
}
public class CoursesTeacher
{
public int Id { set;get;}
public string FullName { set;get;}
public List<CourseVm> Courses { set;get;}
}
and in the view which is strongly typed to a collection CoursesTeacher
#model IEnumerable<CoursesTeacher>`
<table>
#foreach(var t in Model)
{
<tr>
<td>#t.FullName</td>
<td>
<table>
#foreach(var c in t.Courses)
{
<tr><td>#c.Name</td>
<td><button>Some button</button></td>
</tr>
}
</table>
</td>
</tr>
}
</table>

Approve/ Reject Method Not Work In asp.net mvc

I made a method for approving or rejecting registration requests from the user registration form.
When users submit a form, the request becomes pending and then admin has the authority to reject or approve the request; but my method does not work properly, because nothing happen.
The application just refresh the page when I click on the reject or approve button.
Can anyone tell me what's wrong with my code? Code snippets follow.
This is the approval controller
public class ApprovedRegistrationController :BaseAdminController
{
// GET: Admin/ApproveRegistration
public ActionResult Index(string Status)
{ ViewBag.Status = (Status == null ? "P" : Status);
if (Status == null)
{ var register = objBs.registerBs.GetALL().Where(x => x.Approved == "P").ToList();
return View(register); }
else
{ var register = objBs.registerBs.GetALL().Where(x => x.Approved == Status).ToList();
return View(register); }}
public ActionResult Approve(int id)
{ try
{ var myRegistration = objBs.registerBs.GetByID(id);
myRegistration.Approved = "A";
objBs.registerBs.Update(myRegistration);
TempData["Msg"] = "Approved Successfully";
return RedirectToAction("Index"); }
catch (Exception e1)
{ TempData["Msg"] = "Approved Failed: " + e1.Message;
return RedirectToAction("Index");}}
public ActionResult Reject(int id)
{try
{ var myRegistration = objBs.registerBs.GetByID(id);
myRegistration.Approved = "R";
objBs.registerBs.Update(myRegistration);
TempData["Msg"] = "Rejected Successfully";
return RedirectToAction("Index");}
catch (Exception e1)
{ TempData["Msg"] = "Rejection Failed: " + e1.Message;
return RedirectToAction("Index");}}}
Registration Approval or rejection view
#model IEnumerable<XtechWebsite.Models.Registration>
#{
ViewBag.Title = "Index";}
<h2>Index</h2>
<script>
function ConfirmApprove() {
return confirm('Are u sure to accept it?');
}
function ConfirmReject() {
return confirm('Are u sure to reject it?');
}
</script>
<h3>Manage Registration<h3>
#if (TempData["Msg"] != null)
{<h3 #TempData["Msg"].ToString()</h3>
}
<h4>#if (ViewBag.Status == "P")
{<b>#Html.ActionLink("Pending Requests", "Index", new { Status = "P" })</b>
}
else
{
#Html.ActionLink("Pending Requests", "Index", new { Status = "P" })
}
#if (ViewBag.Status == "A")
{
<b>#Html.ActionLink("Approved Requests", "Index", new { Status = "A" })</b>
}
else
{
#Html.ActionLink("Approved Requests", "Index", new { Status = "A" })
}
#if (ViewBag.Status == "R")
{
<b>#Html.ActionLink("Rejected Requests", "Index", new { Status = "R" })</b>
}
else
{
#Html.ActionLink("Rejected Requests", "Index", new { Status = "R" })
}
</h4
<table class="table">
<tr>
<th>Approve/Reject</th>
<th>
#Html.DisplayNameFor(model => model.First_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Last_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Department_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Team_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Select_Members)
</th>
<th>
#Html.DisplayNameFor(model => model.Approved)
</th>
<th>
#Html.DisplayNameFor(model => model.Email_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.Competition.CategoryName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink("Approve", "Approve", new { id = item.Registration_ID }, new { onclick = "return ConfirmApprove();" }) |
#Html.ActionLink("Reject", "Reject", new { id = item.Registration_ID }, new { onclick = "return ConfirmReject();" })
</td>
<td>
#Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Department_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Team_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Select_Members)
</td>
<td>
#Html.DisplayFor(modelItem => item.Approved)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Competition.CategoryName)
</td>
</tr> }
</table>
**Admin Base Contoller**
public class BaseAdminController : Controller
{
// GET: Admin/BaseAdmin
protected AdminBs objBs;
public BaseAdminController()
{
objBs = new AdminBs();
}
}
registerbs class that is used in approval controller
public class RegisterBs
{
private RegisterDb objDb;
public RegisterBs()
{
objDb = new RegisterDb();
}
public IEnumerable<Registration> GetALL()
{
return objDb.GetALL();
}
public Registration GetByID(int Id)
{
return objDb.GetByID(Id);
}
public void Insert(Registration registration)
{
objDb.Insert(registration);
}
public void Delete(int Id)
{
objDb.Delete(Id);
}
public void Update(Registration registration)
{
objDb.Update(registration);
}
}
<b>Registration db class<b>
public class RegisterDb
{
private XtechContext db;
public RegisterDb()
{
db= new XtechContext();
}
public IEnumerable<Registration> GetALL()
{
return db.Registrations.ToList();
}
public Registration GetByID(int Id)
{
return db.Registrations.Find(Id);
}
public void Insert(Registration registration)
{
db.Registrations.Add(registration);
Save();
}
public void Delete(int Id)
{
Registration registration = db.Registrations.Find(Id);
db.Registrations.Remove(registration);
Save();
}
public void Update(Registration registration)
{
db.Entry(registration).State = EntityState.Modified;
}
public void Save()
{
db.SaveChanges();
}
}
this is the interface pic then you easily understand it
You do not call SaveChanges on the context that why your modifications are not persisted to the database.
You may add a call to Save() in your update method.

Categories

Resources