update session data from ViewModel - c#

here I updated my quantity. how I will use or inject this updated quantity?
[HttpGet]
public ActionResult Details(int? id)
{
ViewBag.product = _db.Spray.ToList();
if (id == null)
{
return NotFound();
}
var hi = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);
ProductVm product = new ProductVm
{
Name = hi.Name,
Id = hi.Id,
Image=hi.Image,
Image1=hi.Image1,
Quantity = hi.Quantity,
Price = hi.Price,
};
if (product == null)
{
return NotFound();
}
return View(product);
}
[HttpPost]
[ActionName("Details")]
public async Task <IActionResult> ProductDetails(ProductVm pb)
{
List<Spray> sprays = new List<Spray>();
//if (id == null)
//{
// return NotFound();
//}
//var yes = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);
ProductVm product = new ProductVm()
{
Name = pb.Name,
Id = pb.Id,
Image = pb.Image,
Image1=pb.Image1,
Quantity = pb.Quantity,
Price = pb.Price,
};
if (product == null)
{
return NotFound();
}
sprays = HttpContext.Session.Get<List<Spray>>("sprays");
if (sprays == null)
{
sprays = new List<Spray>();
}
sprays.Add(product);
HttpContext.Session.Set("sprays", sprays);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Cart()
{
List<Spray> sprays = HttpContext.Session.Get<List<Spray>>("sprays");
if (sprays == null)
{
sprays = new List<Spray>();
}
return View(sprays);
}
#model List<Spray>
#{
ViewData["Title"] = "Cart";
}
<div>
<div class="row">
<div class="col-6">
<table class="table table-bordered">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Quantity Update</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<img src="~/#item.Image" width="200px" height="150px" />
</td>
<td>#item.Name</td>
<td>#item.Quantity</td>
<td>#item.Price</td>
<td>
<input type="number" asp-for="#item.Quantity" min="0" max="1000" />
</td>
<td>#(item.Price * item.Quantity)</td>
<td>
<a asp-area="Customer" asp-action="Remove" asp-controller="LaptopShow" asp-route-id="#item.Id" class="btn btn-danger">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="col-6">
<div class="text-right">
<h3>Total Amount</h3>
<h3>Grand Total : #Model.Sum(c => c.Price * c.Quantity)</h3>
<a asp-area="Customer" asp-action="Checkout" asp-controller="Order" class="btn btn-info">Process To CheckOut</a>
</div>
</div>
<div>
<a asp-action="Index" asp-controller="SprayShow" class="btn btn-primary">Back To Home</a>
</div>
</div>
</div>
#*<div>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
<a asp-action="Index">Back to List</a>
</div>*#
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$("input[name='item.Quantity']").change(function () {
//get the new quantity
var newquantity = parseInt($(this).val());
//update the original quantity value
$(this).closest("tr").find("td")[2].innerHTML = newquantity;
//get the price
var price = parseFloat($(this).closest("tr").find("td")[3].innerHTML);
//calculate the total
$(this).closest("tr").find("td")[5].innerHTML = newquantity * price;
//calcule the Grand Total
var grandtotal = 0;
$("tbody").find("tr").each(function (index, item) {
var value = parseFloat($(item).find("td")[5].innerHTML);
grandtotal += value;
});
$(".text-right h3:last").html("Grand Total : " + grandtotal.toString());
});
});
</script>
above code, I change quantity increase and decrease for calculating.but this update value session data could not pick. for that, I am found a problem here to process to checkout problem. I can not found actual quantity data which I updated cart.cshtml.
here my output the updated the quantity using jquery
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HuddsonBay.Data;
using HuddsonBay.Models;
using HuddsonBay.Utility;
using Microsoft.AspNetCore.Mvc;
namespace HuddsonBay.Areas.Customer.Controllers
{
[Area("Customer")]
public class OrderController : Controller
{
private ApplicationDbContext _db;
public OrderController(ApplicationDbContext db)
{
_db = db;
}
[HttpGet]
public IActionResult Checkout()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Checkout(Order anOrder)
{
//session theke data peck
List<Spray> sprays = HttpContext.Session.Get<List<Spray>>("sprays");
if (sprays != null)
{
for each (var mobile in sprays)
{
OrderDetails orderDetails1 = new OrderDetails();
orderDetails1.ProductId = mobile.Id;
anOrder.OrderDetails.Add(orderDetails1);
}
}
anOrder.OrderNo = GetOrderNo();
_db.Orders.Add(anOrder);
await _db.SaveChangesAsync();
HttpContext.Session.Set("sprays", new List<Spray>());
return RedirectToAction(nameof(Checkout));
}
public String GetOrderNo() //for count order number
{
int rowCount = _db.Orders.ToList().Count() + 1;
return rowCount.ToString("000");
}
}
}
above view, the list of item session data can not pick my updated quantity. how I solved this problem. I am facing problem in order of the value of the quantity.
I am beginner, please anyone help.

Here is a demo to show how to pass List to controller with ajax:
Spray:
public class Spray
{
public int Id { get; set; }
public string Image { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public int Price { get; set; }
public int Total { get; set; }
}
Controller:
[HttpGet]
public IActionResult Cart()
{
List < Spray > sprays= new List<Spray> { new Spray { Id = 1, Name = "product1", Price = 10, Quantity = 1, Total = 1,Image="image1.png" }, new Spray { Id = 2, Name = "product2", Price = 20, Quantity = 1, Total = 20,Image="Image2.png" } };
return View(sprays);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendSprays([FromBody]IList<Spray> t) {
return RedirectToAction(nameof(Cart));
}
Cart.cshtml:
<div>
<div class="row">
<div class="col-6">
<table class="table table-bordered" id="myTable">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Quantity Update</th>
<th>Total</th>
<th></th>
<th hidden>Id</th>
<th hidden>ImageValue</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<img src="~/#item.Image" width="200px" height="150px" />
</td>
<td>#item.Name</td>
<td>#item.Quantity</td>
<td>#item.Price</td>
<td>
<input type="number" asp-for="#item.Quantity" min="0" max="1000" />
</td>
<td>#(item.Price * item.Quantity)</td>
<td>
<a asp-area="Customer" asp-action="Remove" asp-controller="LaptopShow" asp-route-id="#item.Id" class="btn btn-danger">
<i class="fas fa-trash"></i>
</a>
</td>
<td hidden>#item.Id</td>
<td hidden>#item.Image</td>
</tr>
}
</tbody>
</table>
</div>
<div class="col-6">
<div class="text-right">
<h3>Total Amount</h3>
<h3>Grand Total : #Model.Sum(c => c.Price * c.Quantity)</h3>
<button onclick="checkout()">Process To CheckOut</button>
#*<a asp-action="Checkout" asp-controller="Test" class="btn btn-info">Process To CheckOut</a>*#
</div>
</div>
<div>
<a asp-action="Index" asp-controller="SprayShow" class="btn btn-primary">Back To Home</a>
</div>
</div>
</div>
#*<div>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
<a asp-action="Index">Back to List</a>
</div>*#
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$("input[name='item.Quantity']").change(function () {
//get the new quantity
var newquantity = parseInt($(this).val());
//update the original quantity value
$(this).closest("tr").find("td")[2].innerHTML = newquantity;
//get the price
var price = parseFloat($(this).closest("tr").find("td")[3].innerHTML);
//calculate the total
$(this).closest("tr").find("td")[5].innerHTML = newquantity * price;
//calcule the Grand Total
var grandtotal = 0;
$("tbody").find("tr").each(function (index, item) {
var value = parseFloat($(item).find("td")[5].innerHTML);
grandtotal += value;
});
$(".text-right h3:last").html("Grand Total : " + grandtotal.toString());
});
});
function checkout() {
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
var sprays = new Array();
//loops through rows
for (i = 1; i < rowLength; i++) {
var tempspray = {};
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//tempspray.image = oCells.item(j).
tempspray.Name = oCells.item(1).innerHTML;
tempspray.Quantity = parseInt(oCells.item(2).innerHTML);
tempspray.Price = parseInt(oCells.item(3).innerHTML);
tempspray.Total = parseInt(oCells.item(5).innerHTML);
tempspray.Id = parseInt(oCells.item(7).innerHTML);
tempspray.Image = oCells.item(8).innerHTML;
sprays.push(tempspray);
}
var token = $('input[name="__RequestVerificationToken"]').val();
var t = JSON.stringify(sprays);
$.ajax({
type: "POST",
url: '#(Url.Action("SendSprays", "Test"))',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: t,
contentType: "application/json; charset=utf-8"
});
}
</script>
result:

Related

How to implement pagination in MVC with bootstrap datepicker?

Friends, I have implemented a solution type ASP.NetCore with a project MVC. I have a view in which I used https://github.com/cloudscribe/cloudscribe.Web.Pagination for pagination. **Honestly I took the example and used it. But I don't get the detail about this code example.
The problem that I have now is that, I have to include filters, like datepicker range. So I am using bootstrap datepicker. But the pagination stopped working.
The pagination gets this parameters in querytrings to work: pageNumber, pageSize and query. When I send the request of the filter date, I can get the dates selected in the controller, but the parameters of pagination get in null.
This is an URL example with pagination working fine: http://localhost/pager?query=1&pagesize=10&pageNumber=2
This is an URL when I send the request in the button 'Apply' with dates range, and pagination died without its parameters like 'query': http://localhost/pager?startDate=11/04/2019&endDate=11/11/2019
I suppose I have to send the current querystring in the request too, but I'm not sure, I'm kind of new at this technology. Thanks for any help.
My view →
#using (Html.BeginForm("Details", "Movements", routeValues: new { pageNumber = #Model.UserMovementsResults.PageNumber, pageSize = #Model.UserMovementsResults.PageSize, query = #Model.Query }, FormMethod.Get))
{
<br />
<div style="border: 2px solid #dee2e6;padding: 5px;width: 50%;">
<br />
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBoxFor(model => model.StartDateFilter, "{0:d MMM yyyy}", new
{
id = "StartDateFilter",
#class = "input-sm form-control",
#readonly = "readonly"
})
<span class="input-group-addon"> To </span>
#Html.TextBoxFor(model => model.EndDateFilter, "{0:d MMM yyyy}", new
{
id = "EndDateFilter",
#class = "input-sm form-control",
#readonly = "readonly"
})
</div>
<br />
<input type="submit" value="Apply" class="btn btn-primary" name="Apply" />
</div>
<br />
<br />
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Date)
</th>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Description)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.UserMovementsResults.Data)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</tbody>
</table>
<div>
<cs-pager cs-paging-pagesize="#Model.UserMovementsResults.PageSize"
cs-paging-pagenumber="#Model.UserMovementsResults.PageNumber"
cs-paging-totalitems="#Model.UserMovementsResults.TotalItems"
cs-pagenumber-param="pageNumber"
cs-show-first-last="true"
cs-suppress-empty-nextprev="true"
cs-remove-nextprev-links="false"
cs-suppress-inactive-firstlast="true"
cs-first-page-text="First"
cs-last-page-text="Last"
cs-pager-li-current-class="active"
cs-pager-li-non-active-class="disabled"
asp-controller="Movements"
asp-route-query="#Model.Query"
asp-route-pagesize="#Model.UserMovementsResults.PageSize"
asp-route-startDateFilter="#Model.StartDateFilter.GetValueOrDefault()"
asp-route-endDateFilter="#Model.EndDateFilter.GetValueOrDefault()"
asp-action="Details" cs-preserve-ambient-querystring="true"></cs-pager>
</div>
}
My Controller (I've tried to set the method HttpGet and HttpPost) →
[HttpGet]
public async Task<IActionResult> Details(int? pageNumber, int? pageSize, int? query, string startDate, string endDate)
{
if (query == null)
{
return NotFound();
}
DateTime startDateFilter = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime endDateFilter = DateTime.Now.EndOfWeek(DayOfWeek.Monday);
var userMovements = await GetUserMovements(user.Id, pageNumber, pageSize, query, startDateFilter, endDateFilter);
return View(userMovements);
}
}
My ViewModel →
public class UserMovementsViewModel
{
private DateTime? endDateFilter;
public UserMovementsViewModel()
{
UserMovementsResults = new PagedResult<UserMovementsResult>();
}
public string Query { get; set; } = string.Empty;
[Key]
public int Id { get; set; }
public int UserId { get; set; }
public PagedResult<UserMovementsResult> UserMovementsResults { get; set; } = null;
public DateTime? StartDateFilter { get; set; }
public DateTime? EndDateFilter
{
get => endDateFilter;
set
{
if (value != null)
{
endDateFilter = value;
endDateFilter = endDateFilter.Value.AddHours(23).AddMinutes(59).AddSeconds(59);
}
}
}
}
public class UserMovementsResult
{
public DateTime Date { get; set; }
public string Description { get; set; }
}
Here is a simple workaround like below:
1.add the following component in _ViewImports.cshtml:
#using cloudscribe.Web.Pagination
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper "*, cloudscribe.Web.Pagination"
2.Model:
public class UserMovements
{
public string Name { get; set; } = string.Empty;
public DateTime Date { get; set; } = DateTime.UtcNow;
public string Description { get; set; } = string.Empty;
}
public class ViewByDateViewModel
{
public ViewByDateViewModel()
{
UserMovements = new PagedResult<UserMovements>();
}
public PagedResult<UserMovements> UserMovements { get; set; }
public string[] Date { get; set; }
}
3.View(ViewByDate.cshtml):
#using System.Linq
#model ViewByDateViewModel
<form class="form-inline" role="form" asp-controller="Home" asp-action="ViewByDate" method="get" asp-antiforgery="false">
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBox("startDate", null, new
{
id = "startDate",
#class = "input-sm form-control",
})
<span class="input-group-addon"> To </span>
#Html.TextBox("endDate", null, new
{
id = "endDate",
#class = "input-sm form-control",
})
</div>
<input type="submit" value="Browse" class="btn btn-default" />
</form>
#if (Model.UserMovements.Data.Any())
{
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model.UserMovements.Data)
{
<tr>
<td>#product.Name</td>
<td>#product.Date</td>
</tr>
}
</tbody>
</table>
<cs-pager cs-paging-pagesize="#Model.UserMovements.PageSize"
cs-paging-pagenumber="#Model.UserMovements.PageNumber"
cs-paging-totalitems="#Model.UserMovements.TotalItems"
cs-pagenumber-param="page"
asp-controller="Home"
asp-action="ViewByDate"
asp-route-categories="#Model.Date.ToCsv()"
asp-route-pagesize="#Model.UserMovements.PageSize"
cs-first-page-text="First"
cs-last-page-text="Last"
cs-previous-page-text="Prev"
cs-next-page-text="Next"></cs-pager>
}
#section Scripts
{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#startDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' });
$("#endDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' })
});
</script>
}
4.Controller:
public class HomeController : Controller
{
private const int DefaultPageSize = 10;
private List<UserMovements> allMovements = new List<UserMovements>();
public HomeController()
{
InitializeMovements();
}
private void InitializeMovements()
{
// Create a list of Movements.
for (var i = 0; i < 527; i++)
{
var userMovements = new UserMovements();
userMovements.Name = "UserMovements " + (i + 1);
var categoryIndex = i % 4;
if (categoryIndex > 2)
{
categoryIndex = categoryIndex - 3;
}
userMovements.Date = DateTime.Now.AddDays(i);
allMovements.Add(userMovements);
}
}
public IActionResult ViewByDate(string startDate, string endDate, int? page)
{
string[] dates = { startDate, endDate };
List<UserMovements> filtered;
var currentPageNum = page.HasValue ? page.Value : 1;
var offset = (DefaultPageSize * currentPageNum) - DefaultPageSize;
var model = new ViewByDateViewModel();
model.Date = dates ?? new string[0];
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
if (startDate == null && endDate == null)
{
filtered = this.allMovements.ToList();
}
else
{
filtered = this.allMovements
.Where(p => p.Date.Date >= DateTime.Parse(startDate) && p.Date.Date <= DateTime.Parse(endDate))
.ToList();
}
model.UserMovements.Data = filtered
.Skip(offset)
.Take(DefaultPageSize)
.ToList();
model.UserMovements.PageNumber = currentPageNum;
model.UserMovements.PageSize = DefaultPageSize;
model.UserMovements.TotalItems = filtered.Count;
return View(model);
}
}
5.Result:
UPDATE:
1.Model:
public class ViewByDateViewModel
{
private DateTime? endDateFilter;
public ViewByDateViewModel()
{
UserMovements = new PagedResult<UserMovements>();
}
public PagedResult<UserMovements> UserMovements { get; set; }
//public string[] Date { get; set; }
public DateTime? StartDateFilter { get; set; }
public DateTime? EndDateFilter
{
get => endDateFilter;
set
{
if (value != null)
{
endDateFilter = value;
endDateFilter = endDateFilter.Value.AddHours(23).AddMinutes(59).AddSeconds(59);
}
}
}
}
2.View:
#using System.Linq
#model ViewByDateViewModel
<form class="form-inline" role="form" asp-controller="Home" asp-action="ViewByDate" method="get" asp-antiforgery="false">
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBox("startDate", null, new
{
id = "startDate",
#class = "input-sm form-control",
})
<span class="input-group-addon"> To </span>
#Html.TextBox("endDate", null, new
{
id = "endDate",
#class = "input-sm form-control",
})
</div>
<input type="submit" value="Browse" class="btn btn-default" />
</form>
#if (Model.UserMovements.Data.Any())
{
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model.UserMovements.Data)
{
<tr>
<td>#product.Name</td>
<td>#product.Date</td>
</tr>
}
</tbody>
</table>
<cs-pager cs-paging-pagesize="#Model.UserMovements.PageSize"
cs-paging-pagenumber="#Model.UserMovements.PageNumber"
cs-paging-totalitems="#Model.UserMovements.TotalItems"
cs-pagenumber-param="page"
asp-controller="Home"
asp-action="ViewByDate"
asp-route-pagesize="#Model.UserMovements.PageSize"
asp-route-startDateFilter="#Model.StartDateFilter"
asp-route-endDateFilter="#Model.EndDateFilter"
cs-first-page-text="First"
cs-last-page-text="Last"
cs-previous-page-text="Prev"
cs-next-page-text="Next"></cs-pager>
}
#section Scripts
{
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#startDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' });
$("#endDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' })
});
</script>
}
3.Controller:
public IActionResult ViewByDate(string startDate, string endDate, int? page)
{
string[] dates = { startDate, endDate };
List<UserMovements> filtered;
var currentPageNum = page.HasValue ? page.Value : 1;
var offset = (DefaultPageSize * currentPageNum) - DefaultPageSize;
var model = new ViewByDateViewModel();
model.StartDateFilter = startDate==null? DateTime.Now:DateTime.Parse(startDate);
model.EndDateFilter = endDate == null ? DateTime.Now : DateTime.Parse(endDate);
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
if (startDate == null && endDate == null)
{
filtered = this.allMovements.ToList();
}
else
{
filtered = this.allMovements
.Where(p => p.Date.Date >= DateTime.Parse(startDate) && p.Date.Date <= DateTime.Parse(endDate))
.ToList();
}
model.UserMovements.Data = filtered
.Skip(offset)
.Take(DefaultPageSize)
.ToList();
model.UserMovements.PageNumber = currentPageNum;
model.UserMovements.PageSize = DefaultPageSize;
model.UserMovements.TotalItems = filtered.Count;
return View(model);
}
if you want to send by url,url would be like:https://localhost:44367/Home/ViewByDate?startdate=11-14-2019&enddate=11-27-2019
If anyone needs this too, here is how I got it → I was missing the setting of the parameters in the controller with ViewBag. Like this → ViewBag.StartDateFilter = starDate; Otherwise, It was becoming at null always, when I tried to change at another page. I don't why.
I used a hidden field too to save the "query" (in my case this is the user id) because when I sent the request submit in the button, this was losing its value too. What a mess !!
Here is a minified version
View:
<script src="~/lib/bootstrap/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<form class="form-inline" role="form" asp-controller="Movements" asp-action="Details" method="get" asp-antiforgery="false" asp-route-query="#ViewBag.Query">
<div>
<div class="input-daterange input-group" id="datepicker">
<span style="font-weight:bold">Date</span> From
#Html.TextBox("startDate", null, new
{
id = "startDate",
#class = "input-sm form-control",
#readonly = "readonly"
})
<span class="input-group-addon"> To </span>
#Html.TextBox("endDate", null, new
{
id = "endDate",
#class = "input-sm form-control",
#readonly = "readonly"
})
</div>
<button asp-route-query="#ViewBag.Query" type="submit" value="Filter" name="Filter">Apply</button>
#Html.Hidden("Query", (object)ViewBag.Query)
</div>
</form>
<br />
<table>
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Date)
</th>
<th>
#Html.DisplayNameFor(model => model.UserMovementsResults.Data.FirstOrDefault().Description)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.UserMovementsResults.Data)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</tbody>
</table>
<div>
<cs-pager cs-paging-pagesize="#Model.UserMovementsResults.PageSize"
cs-paging-pagenumber="#Model.UserMovementsResults.PageNumber"
cs-paging-totalitems="#Model.UserMovementsResults.TotalItems"
cs-pagenumber-param="pageNumber"
asp-controller="Movements"
asp-action="Details"
asp-route-query="#ViewBag.Query"
asp-route-pagesize="#Model.UserMovementsResults.PageSize"
cs-preserve-ambient-querystring="true"
asp-route-startDate="#ViewBag.StartDateFilter"
asp-route-endDate="#ViewBag.EndDateFilter">
</cs-pager>
</div>
Controller:
[HttpGet]
public async Task<IActionResult> Details(int? pageNumber, UserMovementsViewModel userMovementsViewModel)
{
userMovementsViewModel.StartDateFilter = DateTime.ParseExact(userMovementsViewModel.StartDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
userMovementsViewModel.EndDateFilter = DateTime.ParseExact(userMovementsViewModel.EndDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).SetEndOfDay();
var userMovements = await GetUserMovements(pageNumber, userMovementsViewModel).ConfigureAwait(true);
ViewBag.StartDateFilter = userMovementsViewModel.StartDateFilter.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
ViewBag.EndDateFilter = userMovementsViewModel.EndDateFilter.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
ViewBag.Query = userMovementsViewModel.Query;
return View(userMovements);
}
My Class:
public class UserMovementsViewModel
{
public UserMovementsViewModel()
{
UserMovementsResults = new PagedResult<UserMovementsResult>();
}
public string Query { get; set; } = string.Empty;
public PagedResult<UserMovementsResult> UserMovementsResults { get; set; } = null;
public DateTime? StartDateFilter { get; set; }
public DateTime? EndDateFilter { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
}

Model not returning values to controller from dynamically added content?

I have schedule times that can be added dynamically from code behind using Ajax. The user can click an add button and jquery Ajax call should add another set of fields to add a schedule time. From some reason, my model is not returning any values to the controller when I click save.
I've tried using a different model that also includes Date, Start Time and End Time, but the returns no values as well. It seems like the values from the fields are not being posted from the form.
The HTML form
<form asp-action="SetSchedule" asp-controller="Admin" method="post" id="addEventForm">
<table id="scheduleTable">
<thead>
<tr>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
<br />
<button id="addScheduleButton" type="button">Add Schedule Time</button>
<button id="savePendingButton" type="submit" style="margin-left:1em" hidden>Save</button>
</form>
Controller:
[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult SetSchedule(ScheduleViewModel model)
{
_adminManager.SetInterviewSchedule(model);
return RedirectToAction(nameof(ViewSchedule));
}
Model:
public class ScheduleViewModel
{
public List<Schedule> ScheduleItems { get; set; } = new List<Schedule>();
//public InterviewInfoApplicationViewModel InterviewInfo { get; set; } = new InterviewInfoApplicationViewModel();
}
public class Schedule
{
public int Id { get; set; }
public DateTime DateAvailable { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
public bool IsSelected { get; internal set; }
}
Fields to append on ajax call page:
#model Ambassadors.Managers.ViewModels.Admin.Schedule
#{
string rowClass = "pendingScheduleRow";
}
<tr class="#rowClass" style="margin-top:1em">
<td>
#Html.ValidationMessageFor(x => x.DateAvailable)
<input type="text" asp-for="DateAvailable" class="datepickerInput" />
</td>
<td>
#Html.ValidationMessageFor(x => x.StartTime)
<input type="text" asp-for="StartTime" class="timepickerInput" />
</td>
<td>
#Html.ValidationMessageFor(x => x.EndTime)
<input type="text" asp-for="EndTime" class="timepickerInput" />
</td>
<td>
<a class="tooltip deletePendingSchedule" title="Remove Schedule Time" style="cursor:pointer">
<span class="wdn-icon-cancel" aria-hidden="true"></span><span class="wdn-text-hidden">cancel icon</span>
</a>
</td>
</tr>
Script:
require(['jquery', 'jqueryui'], function ($, jqueryui) {
$(function () {
$('body').on('focus', ".datepickerInput", function () {
$(this).datepicker({
controlType: "select",
});
});
$('body').on('focus', ".timepickerInput", function () {
$(this).timepicker({
timeFormat: "hh:mm tt",
interval: 5,
dropdown: true,
scrollbar: true
});
});
$("#addScheduleButton").click(function () {
var nextIndex = $(".pendingScheduleRow").length;
$.ajax({
url: "/Admin/AddScheduleItem",
type: 'POST',
data: {
index: nextIndex
},
success: function (results) {
$("table#scheduleTable tbody").append(results);
$("#savePendingButton").show();
}
});
});
$("#scheduleTable").on("click", ".deletePendingSchedule", function () {
var closestRow = $(this).closest("tr");
$(closestRow).hide();
var visibleRows = $(".pendingScheduleRow:visible").length;
if (visibleRows === 0) {
$("#savePendingButton").hide();
}
});
});
});
Model should return DateAvailable, StartTime and EndTimes to the controller.
Your action receives model type of ScheduleViewModel who has a property of List<Schedule> while your view asp-for="DateAvailable" neither bind to ScheduleViewModel nor bind to List<Schedule>.
Refer to my below demo:
1.AddScheduleItem action to return index to partial view
public IActionResult AddScheduleItem(string index)
{
var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary())
{
{ "index", index }
};
PartialViewResult result = new PartialViewResult()
{
ViewName = "YourPartialViewName",
ViewData = myViewData,
};
return result;
}
2.YourPartailView:
#model ScheduleViewModel
#{
string rowClass = "pendingScheduleRow";
int index = Int32.Parse(#ViewData["index"].ToString());
}
<tr class="#rowClass" style="margin-top:1em">
<td>
#Html.ValidationMessageFor(x => x.ScheduleItems[index].DateAvailable)
<input asp-for="ScheduleItems[index].DateAvailable" class="datepickerInput" />
</td>
<td>
#Html.ValidationMessageFor(x => x.ScheduleItems[index].StartTime)
<input asp-for="ScheduleItems[index].StartTime" class="timepickerInput" />
</td>
<td>
#Html.ValidationMessageFor(x => x.ScheduleItems[index].EndTime)
<input asp-for="ScheduleItems[index].EndTime" class="timepickerInput" />
</td>
<td>
<a class="tooltip deletePendingSchedule" title="Remove Schedule Time" style="cursor:pointer">
<span class="wdn-icon-cancel" aria-hidden="true"></span><span class="wdn-text-hidden">cancel icon</span>
</a>
</td>
</tr>
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial");}

Deleting row from a DataTable in asp.net

I'm trying to get my delete button from a modal popup to delete a row from my local database which is in Visual Studio.
I'm not quite sure how to do this. I'm new to this, so if I'll have to add some data. Please inform me.
This is the Controller:
using MusicBox.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace MusicBox.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//Tab Box
//[HttpGet]
public ActionResult Box()
{
return View();
}
////Dobivanje liste unutar gumba
[HttpGet]
public ActionResult Create()
{
var viewModel = new MusicViewModel();
var genres = new List<Genre>();
var genreList = new List<SelectListItem>();
using (var db = new ApplicationDbContext())
{
genres = db.Genres.ToList();
}
foreach (var genre in genres)
{
genreList.Add(new SelectListItem() { Value = genre.Id.ToString(), Text = genre.Type });
}
viewModel.Genres = genreList;
return View(viewModel);
}
[HttpPost]
public ActionResult Create(MusicViewModel model)
{
//Ovo je validation message
//if (!ModelState.IsValid)
//{
// var viewModel = new MusicViewModel();
// var genres = new List<Genre>();
// var genreList = new List<SelectListItem>();
// using (var db = new ApplicationDbContext())
// {
// genres = db.Genres.ToList();
// }
// foreach (var genre in genres)
// {
// genreList.Add(new SelectListItem() { Value = genre.Id.ToString(), Text = genre.Type });
// }
// viewModel.Genres = genreList;
// return View(viewModel);
//}
var song = new Song
{
GenreId = model.GenreId,
Performer = model.Performer,
Title = model.Title,
Year = model.Year,
YoutubeLink = model.YoutubeLink
};
using (ApplicationDbContext db = new ApplicationDbContext())
{
try
{
db.Songs.Add(song);
db.SaveChanges();
}
catch (Exception e) { }
}
//ovdje ide dodavanje u bazu
return RedirectToAction("List");
}
public ActionResult List()
{
var songs = new List<Song>();
var songList = new List<SongListViewModel>();
try
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
songs = db.Songs.ToList();
foreach (var song in songs)
{
songList.Add(new SongListViewModel
{
Performer = song.Performer,
Song = song.Title,
Genre = song.Genre.Type,
Year = song.Year,
Link = song.YoutubeLink,
Id = song.Id
});
}
}
}
catch (Exception)
{
throw;
}
return View(songList);
}
public ActionResult Edit()
{
return View("Create");
}
}
}
This is the HTML:
#using System.Activities.Expressions
#using System.Web.Mvc.Html
#using MusicBox.Models
#model IEnumerable<SongListViewModel>
#{
ViewBag.Title = "Popis";
}
<h2>Popis pjesama</h2>
<table class="table table-bordered">
<thead class="thead">
<tr>
<th>
Izvođač
</th>
<th>
Pjesma
</th>
<th>
Žanr
</th>
<th>
Godina
</th>
<th>
Youtube Link
</th>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Performer</td>
<td>#item.Song</td>
<td>#item.Genre</td>
<td>#item.Year</td>
<td>Link</td>
<td>
#Html.ActionLink("Edit", "Edit", new {id = item.Id})
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirmSongDelete" data-songId="#item.Id">
Briši
</button>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="confirmSongDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Brisanje pjesme</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Da li sigurno želite izbrisati?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Odustani</button>
<button type="button" class="btn btn-primary">Obriši</button>
</div>
</div>
</div>
</div>
It would be something like that:-
Javascript
<script>
$(document).ready(function () {
$('#confirmSongDelete').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).attr('id');
$("#btnConfirm").attr("id", id);
});
})
function DeleteSong(Id) {
$("div[class='Success']").empty();
$("div[class='failure']").empty();
//call action method
$("#confirmSongDelete").modal("hide");
$.ajax({
url: "#Url.Action("DeleteSong", "HomeController")",
data: { id: Id },
success: function (response) {
if (response != null && response == "True") {
$("#spnSuccessMsg").css("display", "block");
$("#myModalOk").modal('show');
} else {
$("#spnErrorMsg").css("display", "block");
$("#myModalOk").modal('show');
}
window.location.href = window.location.href;
}
});
}
</script>
View
#using System.Activities.Expressions
#using System.Web.Mvc.Html
#using MusicBox.Models
#model IEnumerable<SongListViewModel>
#{
ViewBag.Title = "Popis";
}
<h2>Popis pjesama</h2>
<table class="table table-bordered">
<thead class="thead">
<tr>
<th>
Izvođač
</th>
<th>
Pjesma
</th>
<th>
Žanr
</th>
<th>
Godina
</th>
<th>
Youtube Link
</th>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Performer</td>
<td>#item.Song</td>
<td>#item.Genre</td>
<td>#item.Year</td>
<td>Link</td>
<td>
#Html.ActionLink("Edit", "Edit", new {id = item.Id})
</td>
<td>
<button id="#item.Id" type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirmSongDelete" data-songId="#item.Id">
Briši
</button>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="confirmSongDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Brisanje pjesme</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Da li sigurno želite izbrisati?</p>
</div>
<div class="modal-footer">
<button id="btnConfirm" type="button" class="btn btn-secondary" data-dismiss="modal" onclick="DeleteSong(id);">Odustani</button>
<button type="button" class="btn btn-primary">Obriši</button>
</div>
</div>
</div>
</div>
Controller
public bool DeleteSong()
{
int _deleteResult=0;
string _songId = Request.QueryString["id"];
using (ApplicationDbContext db = new ApplicationDbContext())
{
Song songsMaster = _context.Songs.Single(m => m.SongId == _songId);
_context.Songs.Remove(songsMaster);
_deleteResult= _context.SaveChanges();
}
if(_deleteResult>0)
{
return true;
}
else
{
return false;
}
}

How to put two models in one view [duplicate]

This question already has answers here:
Two models in one view in ASP MVC 3
(12 answers)
Closed 6 years ago.
How can I put two models in one view. Im just new so thats why I cant understand some other answers about this question. Help me please. thank you very much for understanding. I need to finish it in time.
VIEW
#model IEnumerable, PagedList.IPagedLis<ARM2.Models.Institution>
#model PagedList.IPagedList<ARM2.Models.Institution>,
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Insitution";
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
<div class="container-fluid" id="page-content-wrapper">
<h2>INSTITUTION MANAGEMENT</h2>
<br />
<div class="panel panel-default">
<div class="panel-heading">List of Institutions</div>
<div class="panel-body">
<button type="button" class="btn btn-primary pull-right btn-sm" data-toggle="modal" data- target="#addInstitutionModal"> Add &nbsp ; </button>
<br /><br />
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm("Index", "Insitution", FormMethod.Get))
{
<p>
Find by name: #Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
</p>
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.InstitutionID)
</th>
<th>
#Html.ActionLink("Institution Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
#Html.DisplayNameFor(model => model.IIN)
</th>
<th>
#Html.ActionLink("Date Added", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
Action
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.InstitutionID)
</td>
<td>
#Html.DisplayFor(modelItem => item.InstitutionName)
</td>
<td>
#Html.DisplayFor(modelItem => item.IIN)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateAdded)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.InstitutionID }) |
#Html.ActionLink("Details", "Details", new { id=item.InstitutionID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.InstitutionID })
</td>
</tr>
}
</table>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
</div>
</div>
CONTROLLER
namespace ARM2.Controllers
{
public class InstitutionsController : Controller
{
private InstitutionDBContext db = new InstitutionDBContext();
// GET: Institutions
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.IDParm = String.IsNullOrEmpty(sortOrder) ? "ID_desc" : "";
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var insti = from s in db.institutions
select s;
if (!String.IsNullOrEmpty(searchString))
{
insti = insti.Where(s => s.InstitutionName.Contains(searchString));
}
switch (sortOrder)
{
case "ID_desc":
insti = insti.OrderByDescending(s => s.InstitutionID);
break;
case "name_desc":
insti = insti.OrderByDescending(s => s.InstitutionName);
break;
case "Date":
insti = insti.OrderBy(s => s.DateAdded);
break;
case "date_desc":
insti = insti.OrderByDescending(s => s.DateAdded);
break;
default:
insti = insti.OrderBy(s => s.InstitutionID);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(insti.ToPagedList(pageNumber, pageSize));
}
MODEL
namespace ARM2.Models
{
public class Institution
{
public int InstitutionID { get; set; }
public string InstitutionName { get; set; }
public int IIN { get; set; }
public DateTime DateAdded { get; set; }
}
public class InstitutionDBContext : DbContext
{
public DbSet<Institution> institutions { get; set; }
}
}
This is not possible. You should create a ViewModel that includes both these models.

Non-invocable member "HomeController.ServicesList" cannot be used like a method

I want to take the service information from Cshtml . But I get the error .
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ServiceController[] Services;
Services = ServiceController.GetServices();
ServicesViewModel servicesViewModel = new ServicesViewModel();
ServisModel servisler = new ServisModel();
List<ServicesViewModel> list = new List<ServicesViewModel>();
foreach (ServiceController svc in Services)
{
servicesViewModel.ServiceName = svc.ServiceName;
servicesViewModel.ServiceDisplayName = svc.DisplayName;
servicesViewModel.ServiceStatus = svc.Status;
list.Add(servicesViewModel);
}
return View(ServicesList(list));
}
public class ServicesList : IEnumerable
{
List<ServicesViewModel> liste = new List<ServicesViewModel>();
public IEnumerator GetEnumerator()
{
return new MyEnumerator(liste);
}
}
Error: CS1955 Non-invocable member 'HomeController.ServicesList' cannot be used like a method.
This is the class MyEnumerator:
public class MyEnumerator : IEnumerator
{
List<ServicesViewModel> lst = new List<ServicesViewModel>();
int CurrentLocation = -1;
public MyEnumerator(List<ServicesViewModel> p) {
this.lst = p;
}
public object Current
{
get
{
return this.lst[CurrentLocation];
}
}
public bool MoveNext()
{
CurrentLocation++;
return (CurrentLocation < this.lst.Count);
}
public void Reset()
{
CurrentLocation = -1;
}
}
And finally this is the cshtml file:
#model IEnumerable<ExampleProject.ViewModel.ServicesViewModel>
#{
Layout = "~/Views/shared/_Layout.cshtml";
ViewBag.Title = "Sunucu Yönetim Paneli | Ana Sayfa";
ViewBag.Description = "Sunucu Yönetim Paneli";
ViewBag.Keywords = "sunucu, yönetim,paneli";
}
#using (Html.BeginForm("Ara", "Home", FormMethod.Get))
{
<p>
Aranacak Kelime: #Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Ara" />
</p>
}
<table class="table">
<tr>
<th>
Servis Adı
</th>
<th>
Servis Açıklaması
</th>
<th>
Servis Durumu
</th>
<th>
Servis Başlangıç Türü
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#item.ServiceName
#*#Html.DisplayFor(modelItem => item.allServices)*#
</td>
<td>
#*#Html.DisplayFor(modelItem => item.ServiceDisplayName)*#
</td>
<td>
#*#Model.ServiceStatus*#
#*#Html.DisplayFor(modelItem => item.ServiceDisplayName)*#
</td>
<td>
#*#Model.ServiceStartMode*#
#*#Html.DisplayFor(modelItem => item.ServiceDisplayName)*#
</td>
<td>
#*#Html.ActionLink("Başlat", "ServiceStart", "ServicesStartStop", new { #id = item.ServiceName }) |
#Html.ActionLink("Durdur", "ServiceStop", "ServicesStartStop", new { #id = item.ServiceName }) |
#Html.ActionLink("", "", "Başlatma Türü", new { #id = item.ServiceName }, null)*#
#*<input type="submit" value="Başlat" />
<input type="submit" value="Durdur" />
<input type="submit" value="Başlatma Türü" />*#
</td>
</tr>
}
</table>
public class MyEnumerator : IEnumerator
{
List<ServicesViewModel> lst = new List<ServicesViewModel>();
int CurrentLocation = -1;
public MyEnumerator(List<ServicesViewModel> p) {
this.lst = p;
}
public object Current
{
get
{
return this.lst[CurrentLocation];
}
}
public bool MoveNext()
{
CurrentLocation++;
return (CurrentLocation < this.lst.Count);
}
public void Reset()
{
CurrentLocation = -1;
}
}
My Cshtml Class.
#model IEnumerable<ExampleProject.ViewModel.ServicesViewModel>
#{
Layout = "~/Views/shared/_Layout.cshtml";
ViewBag.Title = "Sunucu Yönetim Paneli | Ana Sayfa";
ViewBag.Description = "Sunucu Yönetim Paneli";
ViewBag.Keywords = "sunucu, yönetim,paneli";
}
#using (Html.BeginForm("Ara", "Home", FormMethod.Get))
{
<p>
Aranacak Kelime: #Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Ara" />
</p>
}
<table class="table">
<tr>
<th>
Servis Adı
</th>
<th>
Servis Açıklaması
</th>
<th>
Servis Durumu
</th>
<th>
Servis Başlangıç Türü
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#item.ServiceName
#*#Html.DisplayFor(modelItem => item.allServices)*#
</td>
<td>
#*#Html.DisplayFor(modelItem => item.ServiceDisplayName)*#
</td>
<td>
#*#Model.ServiceStatus*#
#*#Html.DisplayFor(modelItem => item.ServiceDisplayName)*#
</td>
<td>
#*#Model.ServiceStartMode*#
#*#Html.DisplayFor(modelItem => item.ServiceDisplayName)*#
</td>
<td>
#*#Html.ActionLink("Başlat", "ServiceStart", "ServicesStartStop", new { #id = item.ServiceName }) |
#Html.ActionLink("Durdur", "ServiceStop", "ServicesStartStop", new { #id = item.ServiceName }) |
#Html.ActionLink("", "", "Başlatma Türü", new { #id = item.ServiceName }, null)*#
#*<input type="submit" value="Başlat" />
<input type="submit" value="Durdur" />
<input type="submit" value="Başlatma Türü" />*#
</td>
</tr>
}
</table>
So, first error: you try to use ServicesList like a method but it is a class so you need the new keyword before class name.
Second error: in your ServicesList class you don't have a constructor with list as parameters.
To solve the problem you need to change your code in this way:
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ServiceController[] Services;
Services = ServiceController.GetServices();
ServisModel servisler = new ServisModel();
List<ServicesViewModel> list = new List<ServicesViewModel>();
foreach (ServiceController svc in Services)
{
ServicesViewModel servicesViewModel = new ServicesViewModel();
servicesViewModel.ServiceName = svc.ServiceName;
servicesViewModel.ServiceDisplayName = svc.DisplayName;
servicesViewModel.ServiceStatus = svc.Status;
list.Add(servicesViewModel);
}
return View(new ServicesList(list));
}
public class ServicesList : IEnumerable
{
private List<ServicesViewModel> liste = new List<ServicesViewModel>();
public ServicesList(List<ServicesViewModel> l) {
liste = l;
}
public IEnumerator GetEnumerator()
{
return new MyEnumerator(liste);
}
}
Then in your view (cshtml) file you need to change model type from:
#model IEnumerable<ExampleProject.ViewModel.ServicesViewModel>
To:
#model IEnumerable<ExampleProject.[PartThatIDontKnow].ServicesList>
And to solve the issues relative to this change like:
#foreach (var item in Model)
That become:
#foreach (var item in Model.GetEnumerator())
I realy don't understand what you try to do but in this way the code should be build and run without problems. In your cshtml file I can't see any part of code that try to use ServicesList. I hope to be a help. Let me know if all works fine.
Note: when you need to add informations to your question use edit (is under the text of your question) instead of write an answer. I updated your question for you.

Categories

Resources