I have a problem, every time I run my application it gives this error below. I debugged it line by line and saw that the error opens when executing the line "var res = await client.SendAsync(req);"
I've tried everything and I can't find a solution. I've searched everywhere, I've changed from "SendAsync" to everything possible and I can't solve it, I've been trying for 2 days.
My code:
public async Task ListAsync()
{
var client = new HttpClient
{
BaseAddress = new Uri("https://teste.teste1.com.br")
};
client.DefaultRequestHeaders.Add("x-user-email", "victor#teste.com.br");
client.DefaultRequestHeaders.Add("x-api-key", "eyJ0eXAiOiJKV1QiLCJhbGcxYg");
client.DefaultRequestHeaders.Add("x-store-key", "1");
client.DefaultRequestHeaders.Add("accept", "application/json;charset=UTF-8");
// client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, "/app/Api/V1/Products/list");
req.Content = new StringContent("Content-Type", Encoding.UTF8, "application/json");
using var res = await client.SendAsync(req);
res.EnsureSuccessStatusCode();
var responseBody = await res.Content.ReadAsStringAsync();
var root = JsonSerializer.Deserialize<Product>(responseBody);
}
My index(view):
#model IEnumerable<WebConsumoApi.Models.Product>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.sku)
</th>
<th>
#Html.DisplayNameFor(model => model.name)
</th>
<th>
#Html.DisplayNameFor(model => model.description)
</th>
<th>
#Html.DisplayNameFor(model => model.status)
</th>
<th>
#Html.DisplayNameFor(model => model.qty)
</th>
<th>
#Html.DisplayNameFor(model => model.price)
</th>
<th>
#Html.DisplayNameFor(model => model.list_price)
</th>
<th>
#Html.DisplayNameFor(model => model.weight_gross)
</th>
<th>
#Html.DisplayNameFor(model => model.weight_liquid)
</th>
<th>
#Html.DisplayNameFor(model => model.height)
</th>
<th>
#Html.DisplayNameFor(model => model.width)
</th>
<th>
#Html.DisplayNameFor(model => model.length)
</th>
<th>
#Html.DisplayNameFor(model => model.items_per_package)
</th>
<th>
#Html.DisplayNameFor(model => model.brand)
</th>
<th>
#Html.DisplayNameFor(model => model.ean)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.sku)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td>
#Html.DisplayFor(modelItem => item.description)
</td>
<td>
#Html.DisplayFor(modelItem => item.status)
</td>
<td>
#Html.DisplayFor(modelItem => item.qty)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
#Html.DisplayFor(modelItem => item.list_price)
</td>
<td>
#Html.DisplayFor(modelItem => item.weight_gross)
</td>
<td>
#Html.DisplayFor(modelItem => item.weight_liquid)
</td>
<td>
#Html.DisplayFor(modelItem => item.height)
</td>
<td>
#Html.DisplayFor(modelItem => item.width)
</td>
<td>
#Html.DisplayFor(modelItem => item.length)
</td>
<td>
#Html.DisplayFor(modelItem => item.items_per_package)
</td>
<td>
#Html.DisplayFor(modelItem => item.brand)
</td>
<td>
#Html.DisplayFor(modelItem => item.ean)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.sku }) |
#Html.ActionLink("Details", "Details", new { id = item.sku }) |
#Html.ActionLink("Delete", "Delete", new { id = item.sku })
</td>
</tr>
}
</tbody>
</table>
My Interface:
using WebConsumoApi.Models;
namespace WebConsumoApi.Interfaces
{
public interface IProduto
{
Task ListAsync();
Product Create(Product produto);
Product Update(Product produto);
Product GetOne(string Codigo);
Product Delete(string Codigo);
}
}
EDIT 1:
ERROR: ERRO
EDIT 2(CONTROLLER):
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebConsumoApi.Interfaces;
using WebConsumoApi.Models;
namespace WebConsumoApi.Controllers
{
public class ProdutosController : Controller
{
private readonly IProduto _IProduto;
public ProdutosController(IProduto IProduto)
{
_IProduto = IProduto;
}
// GET: ProdutosController
public async Task<ActionResult> Index()
{
return View(_IProduto.ListAsync());
}
// GET: ProdutosController/Details/5
public ActionResult Details(string id)
{
return View(_IProduto.GetOne(id));
}
// GET: ProdutosController/Create
public ActionResult Create()
{
return View();
}
// POST: ProdutosController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Product collection)
{
try
{
_IProduto.Create(collection);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: ProdutosController/Edit/5
public ActionResult Edit(string id)
{
return View(_IProduto.GetOne(id));
}
// POST: ProdutosController/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, Product collection)
{
try
{
_IProduto.Update(collection);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: ProdutosController/Delete/5
public ActionResult Delete(string id)
{
return View(_IProduto.GetOne(id));
}
// POST: ProdutosController/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id, Product collection)
{
try
{
_IProduto.Delete(id);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
}
My class Product:
namespace WebConsumoApi.Models
{
public class Product
{
public string sku { get; set; }
public string name { get; set; }
public string description { get; set; }
public string status { get; set; }
public int qty { get; set; }
public float price { get; set; }
public float? list_price { get; set; }
public float weight_gross { get; set; }
public float weight_liquid { get; set; }
public int height { get; set; }
public int width { get; set; }
public int length { get; set; }
public string items_per_package { get; set; }
public string brand { get; set; }
public string ean { get; set; }
public object ncm { get; set; }
public Category[] categories { get; set; }
public string[] variation_attributes { get; set; }
public Variation[] variations { get; set; }
public string[] images { get; set; }
public Published_Marketplace published_marketplace { get; set; }
public Marketplace_Offer_Links[] marketplace_offer_links { get; set; }
}
}
you have to get data for view, your view model should be like this
#model List<WebConsumoApi.Models.Product>
and controller
private readonly DbContext _context;
public ProdutosController( DbContext context)
{
_context=context;
}
public async Task<ActionResult> Index()
{
List<Product> model= await _context.Products.ToListAsync();
return View(viewModel);
}
and your lambda expressions for the column name should be
<th>
#Html.DisplayNameFor(model => model[0].sku)
</th>
<th>
#Html.DisplayNameFor(model => model[0].name)
</th>
... and so on
I have a list view in my FileManager.cshtml page (code below) and I need to implement sort function to all columns that are displayed on this view. I looked through some examples on the web and YouTube but there are Javascript functions or "hand-made" namespaces. Is it possible to do it without JScript?
Thank you for help!
Function in my controller that displays list view from dbo.Files filtered by logged user ID:
private readonly TextCloudContext Context;
public IActionResult FileManager()
{
var user = _userManager.GetUserId(User);
var items = Context.Files.Where(f => f.UserID == user).ToList();
return View(items);
}
String in TextCloudContext.cs with get and set values in "Files" table from my SQL Server table "Files":
public DbSet<File> Files { get; set; }
File.cs model that initialize values for Db parameter in TextCloudContext and display column names in my FileManagerView.cshtml
public class File
{
public int Id { get; set; }
[Display(Name = "File Name")]
public string Name { get; set; }
public string Data { get; set; }
[Display(Name = "File Type")]
public string Extension { get; set; }
[Display(Name = "Date")]
public string Date { get; set; }
public string UserID { get; set; }
public TextCloudUser User { get; set; }
}
and finally View with table class:
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Extension)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th>
#Html.DisplayName("Actions")
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Extension)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td> - this razor Html doesn't work yet
#Html.ActionLink("Download", "Download", new { fileName = item.ToString() }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
Based on this docs,here is a working demo like below:
View:
#model IEnumerable<File>
<table class="table">
<thead>
<tr>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["NameSortParm"]">#Html.DisplayNameFor(model => model.Name)</a>
</th>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["ExtensionSortParm"]">#Html.DisplayNameFor(model => model.Extension)</a>
</th>
<th>
<a asp-action="FileManager" asp-route-sortOrder="#ViewData["DateSortParm"]">#Html.DisplayNameFor(model => model.Date)</a>
</th>
<th>
#Html.DisplayName("Actions")
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Extension)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.ActionLink("Download", "Download", new { fileName = item.ToString() }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
Controller:
public IActionResult FileManager(string sortOrder)
{
//var user = _userManager.GetUserId(User);
//var items = Context.Files.Where(f => f.UserID == user); //you may change this..
//for easy testing,i just create data manually..
var items = new List<File>()
{
new File(){ Id=1, Data="a", Date="2019-8-9", Extension=".jpg", Name="file1", UserID="1"},
new File(){ Id=1, Data="b", Date="2019-7-9", Extension=".png", Name="file2", UserID="2"},
new File(){ Id=1, Data="c", Date="2019-5-8", Extension=".png", Name="file3", UserID="3"},
new File(){ Id=1, Data="d", Date="2019-4-7", Extension=".jpg", Name="file4", UserID="4"}
}.AsQueryable();
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
ViewData["ExtensionSortParm"] = sortOrder == "Extension" ? "ext_desc" : "Extension";
switch (sortOrder)
{
case "name_desc":
items = items.OrderByDescending(s => s.Name);
break;
case "Date":
items = items.OrderBy(s => s.Date);
break;
case "date_desc":
items = items.OrderByDescending(s => s.Date);
break;
case "Extension":
items = items.OrderBy(s=>s.Extension);
break;
case "ext_desc":
items = items.OrderByDescending(s => s.Extension);
break;
default:
items = items.OrderBy(s => s.Name);
break;
}
return View(items);
}
Result:
Greetings i get this a really strange messenge on the top of my view.
(System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince] System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince] )
I had a database and i use entinty first code made the connection. here is the model view im using:
public IEnumerable<ElencoOmonimi> elencoomonimi { get; set; }
public IEnumerable<ElencoProvince> elencoprovince { get; set; }
public IEnumerable<ElencoImmobiliPerDiritti_E_Quote> elencoimmobiliperditti { get; set; }
public IEnumerable<ElencoComuni> elencocomuni { get; set; }
public IEnumerable<ElencoIntestati> elencointestati { get; set; }
And the contollers:
public ActionResult Index(string searchString, int? id, int? courseID, int? idcom, int? elencoimo)
{
var viewmodel = new mainview();
viewmodel.elencoomonimi = db.ElencoOmonimis
.Where(s => s.Nome.Contains(searchString) || searchString == null || searchString == "")
.Include(s => s.ElencoProvinces.Select(t => t.ElencoImmobiliPerDiritti_E_Quote))
.Include(s => s.ElencoProvinces.Select(t => t.ElencoComunis))
.Include(s => s.ElencoProvinces.Select(t => t.ElencoImmobiliPerDiritti_E_Quote.Select(r => r.ElencoIntestatis)))
////.Include(i => i.ElencoOmonimi)
////.Include(i => i.ElencoImmobiliPerDiritti_E_Quote.Select(t => t.ElencoIntestatis))
////.Include(i => i.ElencoComunis)
.OrderBy(i => i.Id);
if (id != null)
{
ViewBag.elencoomonimiID = id.Value;
viewmodel.elencoprovince = viewmodel.elencoomonimi.Where(
i => i.Id == id.Value).Single().ElencoProvinces;
}
if (idcom != null)
{
ViewBag.ElencoImmobiliperID = idcom.Value;
viewmodel.elencointestati = viewmodel.elencoimmobiliperditti.Where(
x => x.Id == idcom.Value).Single().ElencoIntestatis;
}
//if(elencoimo != null)
// ViewBag.elencoimoobiliID = id.Value
return View(viewmodel);
}
And my view:
#model automasystem.Models.mainview
#{
ViewBag.Title = "Index";
}
Dashboard
#using (Html.BeginForm())
{
#Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" />
}
<table class="table">
<tr>
<th>
Nome
</th>
<th>
Cognome
</th>
<th>
Data Di Nascita
</th>
<th>
Codice Fiscale
</th>
<th></th>
</tr>
#foreach (var item in Model.elencoomonimi)
{
string selectedRow = "";
if (item.Id == ViewBag.elencoomonimiID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.DisplayFor(modelItem => item.CognomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.NomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.Cognome)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataDiNascita)
</td>
<td>
#Html.DisplayFor(modelItem => item.CodiceFiscale)
</td>
#*<td>
#Html.DisplayFor(modelItem => item.Provincia)
</td>
<td>
#Html.DisplayFor(modelItem => item.Fabbricati)
</td>
<td>
#Html.DisplayFor(modelItem => item.Terreni)
</td>*#
#if (item.ElencoProvinces != null)
{
#item.ElencoProvinces
}
<td>
#Html.ActionLink("Select", "Index", new { id = item.Id }) |
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
I don't understand why I get this for every record that its on the database:
System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince] System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince]
You have this in your view (embedded inside a <tr> but not within a <td> so it will actually show above the table!)
#if (item.ElencoProvinces != null)
{
#item.ElencoProvinces
}
That will try to output the string representation of that object, and the value of item.ElencoProvinces.ToString() is obviously
System.Collections.Generic.HashSet`1[automasis.Models.ElencoProvince]
If you don't want ElencoProvinces in your view, just remove those few lines. If you do want it then loop over the hashset, or pull specific information out of a particular item within it, and format it inside appropriate HTML.
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.
THEAPP:
ASP.NET MVC CRUD APPLICATION
Visual Studio 2013
DONE:
Created the filter option by rendering the COLUMN (sector) values into a drop down list. Hence the user can select a sector on from the DROP DOWN LIST & CLICK SUBMIT to FILTER RECORDS in the table
REQUIREMENT:
Filtering Records on a table based on the COLUMN (Sector) values.
In the TABLE of records suppose COLUMN [Sector] has =>
IT, MANAGEMENT, MARKETING, abc, xyz,
It is required to get all the Sector values on more like a NAVIGATION BAR. Once a Sector (MARKETING) is clicked on this LIST the TABLE should list the Only the records with that SECTOR (MARKETING)
Note: User is able to insert new records so is able to create new sector name so links rendered to the navigation bar should be dynamic
As I am a newbie to the language and MVC I have no clue how I could instead of using the DROP DOWN LIST use a LIST VIEW
Controller Code
PipelineController.cshtml
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PipelineApp.Models;
namespace PipelineApp.Controllers
{
public class PipelineController : Controller
{
private PipelineEntities db = new PipelineEntities();
// GET: /Pipeline/
//public ActionResult Index()
//{
// return View(db.Pipelinedatas.ToList());
//}
//CUSTOM GET: /Pipelinedata/Sector filtering
//public ActionResult Index(string sector)
//{
// ViewBag.Sector = (from r in db.Pipelinedatas
// select r.Sector).Distinct();
// var model = from r in db.Pipelinedatas
// where r.Sector == sector || sector == null || sector == ""
// select r;
// return View(model);
//}
//CUSTOM GET: /Pipelinedata/ Sector Filtering/ Sort Order
public ActionResult Index(string sector, string sortOrder, int? page)
{
//Filter Secors ------------------------------
ViewBag.Sector = (from r in db.Pipelinedatas
select r.Sector).Distinct();
//---------------------------------------------
var model = from r in db.Pipelinedatas
where r.Sector == sector || sector == null || sector == ""
select r;
//Sort Order ----------------------------------
ViewBag.CurrentSort = sortOrder; //Paging
ViewBag.EmployerSortParm = String.IsNullOrEmpty(sortOrder) ? "emp_name" : "";
ViewBag.ITOSortParm = String.IsNullOrEmpty(sortOrder) ? "ITO" : "";
ViewBag.JanSortParm = String.IsNullOrEmpty(sortOrder) ? "January" : "";
ViewBag.FebSortParm = String.IsNullOrEmpty(sortOrder) ? "February" : "";
ViewBag.MarSortParm = String.IsNullOrEmpty(sortOrder) ? "March" : "";
ViewBag.AprSortParm = String.IsNullOrEmpty(sortOrder) ? "April" : "";
ViewBag.MaySortParm = String.IsNullOrEmpty(sortOrder) ? "May" : "";
ViewBag.JunSortParm = String.IsNullOrEmpty(sortOrder) ? "June" : "";
ViewBag.JulSortParm = String.IsNullOrEmpty(sortOrder) ? "July" : "";
ViewBag.AugSortParm = String.IsNullOrEmpty(sortOrder) ? "August" : "";
ViewBag.SepSortParm = String.IsNullOrEmpty(sortOrder) ? "September" : "";
ViewBag.OctSortParm = String.IsNullOrEmpty(sortOrder) ? "October" : "";
ViewBag.NovSortParm = String.IsNullOrEmpty(sortOrder) ? "November" : "";
ViewBag.DecSortParm = String.IsNullOrEmpty(sortOrder) ? "December" : "";
ViewBag.SectorSortParm = sortOrder == "sec" ? "ITO" : "sec";
switch (sortOrder)
{
case "emp_name":
model = model.OrderByDescending(s => s.Employer);
break;
case "sec":
model = model.OrderBy(s => s.Sector);
break;
case "ITO":
model = model.OrderByDescending(s => s.ITONumber);
break;
case "January":
model = model.OrderByDescending(s => s.Jan);
break;
case "February":
model = model.OrderByDescending(s => s.Feb);
break;
case "March":
model = model.OrderByDescending(s => s.Mar);
break;
case "April":
model = model.OrderByDescending(s => s.Apr);
break;
case "May":
model = model.OrderByDescending(s => s.May);
break;
case "June":
model = model.OrderByDescending(s => s.Jun);
break;
case "July":
model = model.OrderByDescending(s => s.Jul);
break;
case "August":
model = model.OrderByDescending(s => s.Aug);
break;
case "September":
model = model.OrderByDescending(s => s.Sep);
break;
case "October":
model = model.OrderByDescending(s => s.Oct);
break;
case "November":
model = model.OrderByDescending(s => s.Nov);
break;
case "December":
model = model.OrderByDescending(s => s.Dec);
break;
default:
model = model.OrderBy(s => s.Id);
break;
}
//---------------------------------------------
//Paging --------------------------------------
//int pageSize = 3;
//int pageNumber = (page ?? 1);
//return View(model.ToPagedList(pageNumber, pageSize));
//---------------------------------------------
return View(model);
}
// GET: /Pipeline/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// GET: /Pipeline/Create
public ActionResult Create()
{
return View();
}
// POST: /Pipeline/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,Employer,ITONumber,Description,TECNumber,TECVersion,Level,Credits,Duration,Sector,Status,Approval,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec")] Pipelinedata pipelinedata)
{
if (ModelState.IsValid)
{
db.Pipelinedatas.Add(pipelinedata);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pipelinedata);
}
// GET: /Pipeline/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// POST: /Pipeline/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="Id,Employer,ITONumber,Description,TECNumber,TECVersion,Level,Credits,Duration,Sector,Status,Approval,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec")] Pipelinedata pipelinedata)
{
if (ModelState.IsValid)
{
db.Entry(pipelinedata).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pipelinedata);
}
// GET: /Pipeline/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
if (pipelinedata == null)
{
return HttpNotFound();
}
return View(pipelinedata);
}
// POST: /Pipeline/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Pipelinedata pipelinedata = db.Pipelinedatas.Find(id);
db.Pipelinedatas.Remove(pipelinedata);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
View Code
Index.cshtml
#model IEnumerable<PipelineApp.Models.Pipelinedata>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
<text> Sectors </text>
#Html.DropDownList("sector", new SelectList(ViewBag.Sector))
<input class="btn" type="submit" value="Filter" />
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.ActionLink("Employer", "Index", new { sortOrder = ViewBag.EmployerSortParm })
#*#Html.DisplayNameFor(model => model.Employer)*#
</th>
<th>
#Html.ActionLink("ITONumber", "Index", new { sortOrder = ViewBag.ITOSortParm })
#*#Html.DisplayNameFor(model => model.ITONumber)*#
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.TECNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.TECVersion)
</th>
<th>
#Html.DisplayNameFor(model => model.Level)
</th>
<th>
#Html.DisplayNameFor(model => model.Credits)
</th>
<th>
#Html.DisplayNameFor(model => model.Duration)
</th>
<th>
#Html.ActionLink("Sector", "Index", new { sortOrder = ViewBag.SectorSortParm })
#*#Html.DisplayNameFor(model => model.Sector)*#
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th>
#Html.DisplayNameFor(model => model.Approval)
</th>
<th>
#Html.ActionLink("Jan", "Index", new { sortOrder = ViewBag.JanSortParm })
#*#Html.DisplayNameFor(model => model.Jan)*#
</th>
<th>
#Html.ActionLink("Feb", "Index", new { sortOrder = ViewBag.FebSortParm })
#*#Html.DisplayNameFor(model => model.Feb)*#
</th>
<th>
#Html.ActionLink("Mar", "Index", new { sortOrder = ViewBag.MarSortParm })
#*#Html.DisplayNameFor(model => model.Mar)*#
</th>
<th>
#Html.ActionLink("Apr", "Index", new { sortOrder = ViewBag.AprSortParm })
#*#Html.DisplayNameFor(model => model.Apr)*#
</th>
<th>
#Html.ActionLink("May", "Index", new { sortOrder = ViewBag.MaySortParm })
#*#Html.DisplayNameFor(model => model.May)*#
</th>
<th>
#Html.ActionLink("Jun", "Index", new { sortOrder = ViewBag.JunSortParm })
#*#Html.DisplayNameFor(model => model.Jun)*#
</th>
<th>
#Html.ActionLink("Jul", "Index", new { sortOrder = ViewBag.JulSortParm })
#*#Html.DisplayNameFor(model => model.Jul)*#
</th>
<th>
#Html.ActionLink("Aug", "Index", new { sortOrder = ViewBag.AugSortParm })
#*#Html.DisplayNameFor(model => model.Aug)*#
</th>
<th>
#Html.ActionLink("Sep", "Index", new { sortOrder = ViewBag.SepSortParm })
#*#Html.DisplayNameFor(model => model.Sep)*#
</th>
<th>
#Html.ActionLink("Oct", "Index", new { sortOrder = ViewBag.OctSortParm })
#*#Html.DisplayNameFor(model => model.Oct)*#
</th>
<th>
#Html.ActionLink("Nov", "Index", new { sortOrder = ViewBag.NovSortParm })
#*#Html.DisplayNameFor(model => model.Nov)*#
</th>
<th>
#Html.ActionLink("Dec", "Index", new { sortOrder = ViewBag.DecSortParm })
#*#Html.DisplayNameFor(model => model.Dec)*#
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employer)
</td>
<td>
#Html.DisplayFor(modelItem => item.ITONumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.TECNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.TECVersion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Level)
</td>
<td>
#Html.DisplayFor(modelItem => item.Credits)
</td>
<td>
#Html.DisplayFor(modelItem => item.Duration)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sector)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.DisplayFor(modelItem => item.Approval)
</td>
<td>
#Html.DisplayFor(modelItem => item.Jan)
</td>
<td>
#Html.DisplayFor(modelItem => item.Feb)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mar)
</td>
<td>
#Html.DisplayFor(modelItem => item.Apr)
</td>
<td>
#Html.DisplayFor(modelItem => item.May)
</td>
<td>
#Html.DisplayFor(modelItem => item.Jun)
</td>
<td>
#Html.DisplayFor(modelItem => item.Jul)
</td>
<td>
#Html.DisplayFor(modelItem => item.Aug)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sep)
</td>
<td>
#Html.DisplayFor(modelItem => item.Oct)
</td>
<td>
#Html.DisplayFor(modelItem => item.Nov)
</td>
<td>
#Html.DisplayFor(modelItem => item.Dec)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
references:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/filter-records-in-mvc/
http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
Simply use ajax to invoke the action method "Index", in your case, on click of a tab in the navigation bar. Your ajax code would look something like this.
$.ajax({
type: "GET",
url: "/SomeController/Index",
data: { 'sector': selectedSector },
success: function (data) {
// Here you can assign the partial view returned to an encompassing div
$('#sectorDiv').html(data);
},
error: function (xhr, status, message) {
}
});
#using (Ajax.BeginForm("Index",new AjaxOptions { UpdateTargetId = "result" }))
{
#Html.DropDownList("sector", new SelectList(ViewBag.Sector), new { #class = "chzn-select select-block-level" })
<input class="btn" type="submit" value="Filter" />
}
<div id="result">
#Html.Partial("gridPartial")
</div>