WebGrid binding in GET method but not in POST - c#

While binding the List of values from GET method the WebGrid is displaying the data and same is not displaying in POST method.
Controller:
[HttpGet]
public ActionResult Index()
{
ObservableCollection<Product> inventoryList = new ObservableCollection<Product>();
inventoryList.Add(new Product { Id = "P101", Name = "Computer", Description = "All type of computers", Quantity = 800 });
inventoryList.Add(new Product { Id = "P102", Name = "Laptop", Description = "All models of Laptops", Quantity = 500 });
inventoryList.Add(new Product { Id = "P103", Name = "Camera", Description = "Hd cameras", Quantity = 300 });
inventoryList.Add(new Product { Id = "P104", Name = "Mobile", Description = "All Smartphones", Quantity = 450 });
inventoryList.Add(new Product { Id = "P105", Name = "Notepad", Description = "All branded of notepads", Quantity = 670 });
inventoryList.Add(new Product { Id = "P106", Name = "Harddisk", Description = "All type of Harddisk", Quantity = 1200 });
inventoryList.Add(new Product { Id = "P107", Name = "PenDrive", Description = "All type of Pendrive", Quantity = 370 });
return View(inventoryList);
}
[HttpPost]
public ActionResult Reports(string name)
{
ObservableCollection<Product> inventoryList = new ObservableCollection<Product>();
inventoryList.Add(new Product { Id = "P101", Name = "Computer", Description = "All type of computers", Quantity = 800 });
inventoryList.Add(new Product { Id = "P102", Name = "Laptop", Description = "All models of Laptops", Quantity = 500 });
inventoryList.Add(new Product { Id = "P103", Name = "Camera", Description = "Hd cameras", Quantity = 300 });
inventoryList.Add(new Product { Id = "P104", Name = "Mobile", Description = "All Smartphones", Quantity = 450 });
inventoryList.Add(new Product { Id = "P105", Name = "Notepad", Description = "All branded of notepads", Quantity = 670 });
inventoryList.Add(new Product { Id = "P106", Name = "Harddisk", Description = "All type of Harddisk", Quantity = 1200 });
inventoryList.Add(new Product { Id = "P107", Name = "PenDrive", Description = "All type of Pendrive", Quantity = 370 });
return View(inventoryList);
}
View:
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("Id", format: (item) => item.GetSelectLink(item.Id)),
grid.Column("Name", " Name"),
grid.Column("Description", "Description", style: "description"),
grid.Column("Quantity", "Quantity")
))
</div>
Can someone help me in this?

Related

Linq with inner join and grouping

Sorry, this is the kind of question that will annoy the experts, but I've been searching for similar cases and I'm sure they exist, but I'm simply not good enough to recognize what applies to my scenario.
I have two tables, where there's a 1-n relation between MeasuresSet and Measure :
MeasuresSet {
Id : Guid
Date : DateTime
}
Measure {
Id : Guid
MeasuresSetId : Guid
MeasureCategory : string
Value : double
VehicleName: string
}
MeasuresSet is a group of measures that were performed on the same day, hence the date.
Each row in table Measure represents a specific measure that was performed on the vehicle. For example it could be have MeasureCategory "tyre pressure" and have a corresponding value in psi.
In other words : Each vehicle has many measures, of same or different categories, performed on the same day or on different days.
I want to be able to write a query that means "Give me all the measures that were performed for Vehicle 'Mike's car', but group on MeasureCategory so that I get only the most recent value of each MeasureCategory."
The issue is that the date is stored in MeasuresSet, not Measure. Unfortunately I get lost in the join and the grouping.
I would have imagined that this would be the correct query, but the syntax is incorrect :
from MeasuresSet
join Measure
on MeasuresSet.Id equals Measure.MeasuresSetId //your typical inner join
where VehicleName == "Mike's car"
group Measure by Measure.MeasureCategory into g
select new ResultType {
MeasureCategory : g.Key,
Date: g.OrderByDescending(data => data.Date).First().Date,
Value: g.OrderByDescending(data => data.Date).First().Value,
};
public class MeasuresSet
{
public string Id { get; set; } //: Guid
public DateTime Day { get; set; } //: DateTime
}
public class Measure
{
public string Id { get; set; }//: Guid
public string MeasuresSetId { get; set; }//: Guid
public string MeasureCategory { get; set; } //: string
public double Value { get; set; } //: double
public string VehicleName { get; set; }//: string
}
var measureSets = new List<MeasuresSet>() {
new MeasuresSet() { Daisy = DateTime.Today, Id = "GUID-0" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(1), Id = "GUID-1" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(2), Id = "GUID-2" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(3), Id = "GUID-3" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(4), Id = "GUID-4" }};
var measures = new List<Measure>() {
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-0", Value = 10 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-0", Value = 11 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-0", Value = 12 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-1", Value = 20 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-1", Value = 21 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-1", Value = 22 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-2", Value = 30 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-2", Value = 31 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-2", Value = 32 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-3", Value = 40 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-3", Value = 41 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-3", Value = 42 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-4", Value = 50 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-4", Value = 51 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-4", Value = 52 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-0", Value = 110 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-0", Value = 111 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-0", Value = 112 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-1", Value = 220 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-1", Value = 221 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-1", Value = 222 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-2", Value = 330 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-2", Value = 331 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-2", Value = 332 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-3", Value = 440 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-3", Value = 441 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-3", Value = 442 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-4", Value = 550 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-4", Value = 551 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-4", Value = 552 }};
var result = from set in (from measureSet in measureSets
join measure in measures
on measureSet.Id equals measure.MeasuresSetId
select new
{
Day = measureSet.Day,
ParentId = measureSet.Id,
MeasureCategory = measure.MeasureCategory,
Id = measure.Id,
Value = measure.Value,
VehicleName = measure.VehicleName
})
where set.VehicleName == "Mike's car"
group set by set.MeasureCategory into g
select new
{
MeasureCategory = g.Key,
Day = g.Max(x => x.Day),
Value = g.First(x => x.Day == g.Max(y => y.Day)).Value
};
RESULTS :
Mike's car
tyre pressure | 04/06/2020 00:00:00 | 50
engine | 04/06/2020 00:00:00 | 51
air conditioner | 04/06/2020 00:00:00 | 52
NOT Mike's car
tyre pressure | 02/06/2020 00:00:00 | 330
engine | 03/06/2020 00:00:00 | 441
air conditioner | 04/06/2020 00:00:00 | 552

Case Condition with GroupBy in Linq for duplicate records

I have a list of records where I need to filter the list for duplicate records and take only one record with AddressType = "POST".
Let me show your the example:
class Test
{
public string Id {get; set;}
public string Name {get; set;}
public string AddressType {get; set;}
}
This is the data I have:
var data = new List<Test>{
new Test {Id = "1", Name = "Test11", AddressType = "POST" },
new Test {Id = "1", Name = "Test12", AddressType = "STREET" },
new Test {Id = "2", Name = "Test122", AddressType = "POST" },
new Test {Id = "3", Name = "Test123", AddressType = "POST" },
new Test {Id = "4", Name = "Test1", AddressType = "POST" },
new Test {Id = "4", Name = "Test1", AddressType = "POST" },
new Test {Id = "5", Name = "Test11", AddressType = null }
};
I'm trying to remove the duplicate records based on Id and AdressType = "POST" with this query:
var filteredData = data.GroupBy(x => x.Id).Select(x => x.First()).ToList();
This removes the duplicacy but I want to take the record with AddressType = "POST" and the above query randomly picked the First record. I have tried another thing where with this query but it is not working:
var filteredData = data.GroupBy(x => x.Id).Select(x => x.First()).Where(x => x.AddressType == "POST").ToList();
Expected Output:
Test {Id = "1", Name = "Test11", AddressType = "POST" },
Test {Id = "2", Name = "Test122", AddressType = "POST" },
Test {Id = "3", Name = "Test123", AddressType = "POST" },
Test {Id = "4", Name = "Test1", AddressType = "POST" },
Test {Id = "5", Name = "Test11", AddressType = null }
Is there anything I'm missing?
Update: Thanks to the solutions below, it worked but in case of any null value in the list. It breaks. So by adding FirstOrDefault() I'm able to handle the null error but the details of that row is not getting added to the result. Any thoughts on that?
Try putting the predicate inside the call to first:
var filteredData = data
.GroupBy(x => x.Id)
.Select(x => x.FirstOrDefault(x => x.AddressType == "POST"))
.ToList();
You can group by your selected columns then select FirstOrDefault(). try bellow;
var list = data.GroupBy(x => new { x.Id, x.AddressType })
.Select(x => x.FirstOrDefault(a => a.AddressType == "POST" || a.AddressType == null))
.Where(y => y != null)
.ToList();
Same as your expected result:
ID Name AddressType
1 Test11 POST
2 Test122 POST
3 Test123 POST
4 Test1 POST
5 Test11 null
Hope the answer helps someone.

Entity Framework not sure how to retrieve Guid from one table to use in another

I am using Entity Framework to create my database. I have a table called "Departments" that seed first and then add two users. I need to use the Id from the department table to seed the user table.
context.Department.AddOrUpdate(x => x.Id,
new Department() { Id = Guid.NewGuid(), Name = "System", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Estimating", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Assembly", ImageNameLight = "dep-assy-off", ImageNameDark = "dep-assy-on" },
new Department() { Id = Guid.NewGuid(), Name = "Project Engineering", ImageNameLight = "dep-pe-off", ImageNameDark = "dep-pe-on" },
);
var firstOrDefault = context.Department.FirstOrDefault(d => d.Name == "System");
if (firstOrDefault != null)
{
var user = new ApplicationUser
{
UserName = "sysadmin",
Email = "sysadmin#noemail.com",
EmailConfirmed = true,
FirstName = "System",
LastName = "Admin",
RoleId = adminRole.Id,
DateCreated = DateTime.Now,
DepartmentId = firstOrDefault.Id
};
This is what I have so far but it does not work because the user is never created.
You have to save to your context first or else the seed will never work try this :
context.Department.AddOrUpdate(x => x.Id,
new Department() { Id = Guid.NewGuid(), Name = "System", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Estimating", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Assembly", ImageNameLight = "dep-assy-off", ImageNameDark = "dep-assy-on" },
new Department() { Id = Guid.NewGuid(), Name = "Project Engineering", ImageNameLight = "dep-pe-off", ImageNameDark = "dep-pe-on" },
);
context.SaveChanges();
//Do whatever with your new context

How to fill database from buttonclick

I have a database which i would like to fill with a filler-method. I wish to call on this method from the Index-view in my MVC-project. I have tested that the method works by running it each time the index.cshtml is run, and it fills the table. The only problem with this is that if I refresh the index-page, the table gets filled with the exact same data once again. Which results in me getting two of every item.
So I have come to the conclusion that I want to bind my filler()-method to a button on the index-page to fill the table. My question is then:
How do I directly bind a method to a button in my project?
Extra info:
The filler-method is in its own class called DBFiller.cs, and when I set it to run on index launch I added DBfiller.filler() in the actionresult of my controller.
Code:
DBFiller.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Oblig1.BLL;
using Oblig1.Model;
using Oblig1.DAL;
namespace Oblig1
{
public class DBFiller
{
public void Filler()
{
var userDb = new UserBLL();
var itemDb = new ItemBLL();
var city1 = new Cities();
var city2 = new Cities();
var city3 = new Cities();
city1.Cityname = "Oslo";
city1.Postcode = "9382";
city2.Cityname = "Trondheim";
city2.Postcode = "2301";
city3.Cityname = "Bergen";
city3.Postcode = "1723";
var user1 = new Users()
{
Address = "Moroveien 7",
Firstname = "Martin",
Surname = "Hermansen",
Email = "mh#mh.no",
Password = "mhmhmh",
Phonenr = "93929392",
Postcode = "9382",
cities = city1
};
var user2 = new Users()
{
Address = "Bakvendtgata 8",
Firstname = "Hanne",
Surname = "Lande",
Email = "hl#hl.no",
Password = "hlhlhl",
Phonenr = "82711212",
Postcode = "2301",
cities = city2
};
var user3 = new Users()
{
Address = "Fisefin Aveny 14",
Firstname = "Voldemort",
Surname = "Olsen",
Email = "vo#vo.no",
Password = "vovovo",
Phonenr = "12672891",
Postcode = "1723",
cities = city3
};
var item1 = new Items()
{
Currentstock = 40,
Itemname = "Blanding",
Itemprice = 99,
Itemtype = "Pasta",
PictureURL = "/img/pasta_blanding.png",
Itemid = 78
};
var item2 = new Items()
{
Currentstock = 17,
Itemname = "Fusilli",
Itemprice = 119,
Itemtype = "Pasta",
PictureURL = "/img/pasta_fusilli.png",
Itemid = 63
};
var item3 = new Items()
{
Currentstock = 80,
Itemname = "Farfalle",
Itemprice = 69,
Itemtype = "Pasta",
PictureURL = "/img/pasta_farfalle.png",
Itemid = 30
};
var item4 = new Items()
{
Currentstock = 63,
Itemname = "Colored Fusilli #1",
Itemprice = 45,
Itemtype = "Pasta",
PictureURL = "/img/pasta_fusilli_farget.png",
Itemid = 22
};
var item5 = new Items()
{
Currentstock = 3,
Itemname = "Colored Fusilli #2",
Itemprice = 33,
Itemtype = "Pasta",
PictureURL = "/img/pasta_fusilli_farget2.png",
Itemid = 98
};
var item6 = new Items()
{
Currentstock = 77,
Itemname = "Macaroni",
Itemprice = 25,
Itemtype = "Pasta",
PictureURL = "/img/pasta_macaroni.png",
Itemid = 76
};
var item7 = new Items()
{
Currentstock = 80,
Itemname = "Measure",
Itemprice = 299,
Itemtype = "Tools",
PictureURL = "/img/pasta_messure.png",
Itemid = 59
};
var item8 = new Items()
{
Currentstock = 14,
Itemname = "Multitool",
Itemprice = 499,
Itemtype = "Tool",
PictureURL = "/img/pasta_multitool.png",
Itemid = 69
};
var item9 = new Items()
{
Currentstock = 88,
Itemname = "Penne",
Itemprice = 19,
Itemtype = "Pasta",
PictureURL = "/img/pasta_penne.png",
Itemid = 79
};
var item10 = new Items()
{
Currentstock = 45,
Itemname = "Roller",
Itemprice = 59,
Itemtype = "Tool",
PictureURL = "/img/pasta_ruller.png",
Itemid = 79
};
var item11 = new Items()
{
Currentstock = 179,
Itemname = "Spoon",
Itemprice = 39,
Itemtype = "Tool",
PictureURL = "/img/pasta_sleiv.png",
Itemid = 110
};
var item12 = new Items()
{
Currentstock = 17,
Itemname = "Spagetti",
Itemprice = 9,
Itemtype = "Pasta",
PictureURL = "/img/pasta_penne.png",
Itemid = 79
};
itemDb.registerItem(item1);
itemDb.registerItem(item2);
itemDb.registerItem(item3);
itemDb.registerItem(item4);
itemDb.registerItem(item5);
itemDb.registerItem(item6);
itemDb.registerItem(item7);
itemDb.registerItem(item8);
itemDb.registerItem(item9);
itemDb.registerItem(item10);
itemDb.registerItem(item11);
itemDb.registerItem(item12);
userDb.setIn(user1);
userDb.setIn(user2);
userDb.setIn(user3);
}
}
}
My attempt at adding it in the index-launcher in my User-Controller:
namespace Oblig1.Controllers
{
public class UserController : Controller
{
public ActionResult Index()
{
var model = new UserBLL();
var filler = new DBFiller();
filler.Filler();
List<Item> allItems = model.getItems();
return PartialView(allItems);
}
}
}
Index.cshtml if it helps any:
#using Oblig1
#model IEnumerable<Oblig1.Model.Item>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<br />
<head>
<title>Index</title>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
#if (Model != null)
{
<div class="row">
#foreach(var item in Model)
{
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img src="#item.pictureURL" alt="...">
<div class="caption">
<h3>#item.itemname</h3>
<p>Antall på lager: #item.currentstock<br />kr #item.itemprice,00</p>
<button class="btn btn-success">#Html.ActionLink("Add to Cart", "AddToCart", new { id = item.itemid }, null)</button>
</div>
</div>
</div>
}
</div>
}
Attempt at filler-call by JS:
#model IEnumerable<Oblig1.Model.Item>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<br />
<head>
<title>Index</title>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/jscript">
$('#fill').click(function () {
var url = "/UserController/Filler";
$.post( url);
});
</script>
</head>
<button class="btn btn-success" id="fill" value="Fill Database"> </button>
Controller:
public ActionResult Filler()
{
var filler = new DBFiller();
filler.Filler();
return View("Index");
}
You can move the logic of filling to another action method and call it using jquery Ajax call on the click of the button
EDIT:
Please refer the below link for sample
http://www.itorian.com/2013/02/jquery-ajax-get-and-post-calls-to.html
Basically below is the code to link the click of your button with Action method
<script type="text/javascript">
$(document).ready(function()
{
$('#ButtonID').click(function () {
var url = "/ControllerName/YourActionMethod";
$.post( url);
});
});
Add the above code in your page with appropriate url and button id

Keep selected value in strongly-type dropdownlist after form submitted

In a view I'm using 3 dropdownlist strongly-typed to a model like this:
#using (Html.BeginForm())
{
<p>Filter by rarity: #Html.DropDownListFor(_item => _item.mRarity, Model.mRarityList, new {#id = "cardRarity"})
Filter by type: #Html.DropDownListFor(_item => _item.mType, Model.mTypeList, new {#id = "cardType"})
Filter by color: #Html.DropDownListFor(_item => _item.mColor, Model.mColorList, new {#id = "cardColor"})
</p>
}
Here's the view in which the thing is displayed:
#model PagedList.IPagedList<MvcMagicAdmin.Utilities.CardDisplay>
#{
ViewBag.Title = "Cards Display Results";
}
<h2>
Cards Display Results
</h2>
<script type="text/javascript">
$(document).ready(function () {
$('#cardRarity').change(function () {
var showCardRarity = $(this).val();
alert(showCardRarity);
var showCardType = $('#cardType').val();
var showCardColor = $('#cardColor').val();
refreshResults(showCardRarity, showCardType, showCardColor);
});
$('#cardType').change(function () {
var showCardType = $(this).val();
alert(showCardType);
var showCardRarity = $('#cardRarity').val();
var showCardColor = $('#cardColor').val();
refreshResults(showCardRarity, showCardType, showCardColor);
});
$('#cardColor').change(function () {
var showCardColor = $(this).val();
alert(showCardColor);
var showCardRarity = $('#cardRarity').val();
var showCardType = $('#cardType').val();
refreshResults(showCardRarity, showCardType, showCardColor);
});
function refreshResults(rarity, type, color) {
$.get("#Url.Action("DisplayCardsResults", "Card")", {
_page: 1,
_sortOrder: "#ViewBag._sortOrder",
_rarity: rarity,
_type: type,
_color: color,
}, function(data) {
$("#resultsDiv").html(data);
});
}
});
</script>
<div>
<div class="float-left">
<p>#Html.ActionLink("Make a new search", "SearchCardsAdvanced")</p>
</div>
<div class="float-right">
<p><span class="bold baseFontSize">Legend: </span>Details #Html.Image("~\\Images\\Functional\\Icons\\detailsIcon.jpg", "details", new { #class = "centerVert" } )
Edit #Html.Image("~\\Images\\Functional\\Icons\\editIcon.png", "edit", new {#class = "centerVert"} )
Delete #Html.Image("~\\Images\\Functional\\Icons\\trashIcon.png", "delete", new {#class = "centerVert"} )</p>
</div>
<div class="clear"></div>
</div>
#{
Html.RenderAction("FilterCardsResults", "PartialViews");
}
<div id="resultsDiv">
#{
Html.RenderPartial("ResultsTable", Model);
}
</div>
So, yes, I am calling a partial view from another controller because I pass a model which is not included in the Original List of models.
The view is generated like this:
private static readonly CardsFilters mCardsFilters = new CardsFilters();
public ActionResult FilterCardsResults()
{
return PartialView("Filters/FilterCardsResults", mCardsFilters);
}
Here's the model on which the data is built:
public class CardsFilters
{
public string mRarity { get; set; }
public IEnumerable<SelectListItem> mRarityList { get; set; }
public string mType { get; set; }
public IEnumerable<SelectListItem> mTypeList { get; set; }
public string mColor { get; set; }
public IEnumerable<SelectListItem> mColorList { get; set; }
public CardsFilters()
{
List<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem() {Value = "All", Text = "All"},
new SelectListItem() {Value = "Land", Text = "Land"},
new SelectListItem() {Value = "Common", Text = "Common"},
new SelectListItem() {Value = "Uncommon", Text = "Uncommon"},
new SelectListItem() {Value = "Rare", Text = "Rare"},
new SelectListItem() {Value = "Mythic Rare", Text = "Mythic Rare"},
new SelectListItem() {Value = "Special", Text = "Special"}
};
mRarityList = new SelectList(items, "Value", "Text");
items = new List<SelectListItem>
{
new SelectListItem(){ Value = "All", Text = "All"},
new SelectListItem(){ Value = "Artifact", Text = "Artifact"},
new SelectListItem(){ Value = "Instant", Text = "Instant"},
new SelectListItem(){ Value = "Creature", Text = "Creature"},
new SelectListItem(){ Value = "Land", Text = "Land"},
new SelectListItem(){ Value = "Planeswalker", Text = "Planeswalker"},
new SelectListItem(){ Value = "Enchantment", Text = "Enchantment"},
new SelectListItem(){ Value = "Sorcery", Text = "Sorcery"},
new SelectListItem(){ Value = "Tribal", Text = "Tribal"},
};
mTypeList = new SelectList(items, "Value", "Text");
items = new List<SelectListItem>
{
new SelectListItem(){ Value = "All", Text = "All"},
new SelectListItem(){ Value = "White", Text = "White"},
new SelectListItem(){ Value = "Red", Text = "Red"},
new SelectListItem(){ Value = "Green", Text = "Green"},
new SelectListItem(){ Value = "Blue", Text = "Blue"},
new SelectListItem(){ Value = "Black", Text = "Black"},
new SelectListItem(){ Value = "Gold", Text = "Gold"},
new SelectListItem(){ Value = "Colorless", Text = "Colorless"},
};
mColorList = new SelectList(items, "Value", "Text");
}
}
And, finally, the post method called in the controller:
public ActionResult DisplayCardsResults(int? _page, string _sortOrder, string _rarity = "", string _type = "", string _color = "")
{
ViewBag._rarity = _rarity;
ViewBag._color = _color;
ViewBag._type = _type;
if (Request.HttpMethod != "GET")
{
_page = 1;
}
if (mListCards.Count == 0)
{
TempData[MessageDomain.Tags.TEMPDATA_MESSAGE_ERROR] = NODATAFILTERERRORMESSAGE;
}
int pageNumber = (_page ?? 1);
if (Request.IsAjaxRequest())
{
mListCardsToShow = GetListCardsToShow(_rarity, _color, _type);
return PartialView("ResultsTable", mListCardsToShow.ToPagedList(pageNumber, ValueDomain.PAGE_SIZE));
}
if (mListCardsToShow.Count > 0)
{
mListCardsToShow = SortListOrder(_sortOrder, mListCardsToShow);
return View(mListCardsToShow.ToPagedList(pageNumber, ValueDomain.PAGE_SIZE));
}
if (mListCards.Count > 0)
{
mListCards = SortListOrder(_sortOrder, mListCards);
}
return View(mListCards.ToPagedList(pageNumber, ValueDomain.PAGE_SIZE));
}
The dropdownlist works very fine, except for one reason. When I post back the form, all the values selected in the dropdownlist resets to "All", and I'd like to keep them selected. How might I do this?
You must make shure that you are correctly binding your return model into the view.
I took your example and included it into a simple project, that is working ok:
The controller with a simple POST:
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var model = new CardsFiltersViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(CardsFiltersViewModel model)
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(model);
}
public ActionResult About()
{
return View();
}
}
It returns the object the you presented above.
The View is the exact same as your code.
#using (Html.BeginForm())
{
<p>
Filter by rarity: #Html.DropDownListFor(_item => _item.mRarity, Model.mRarityList, new { #id = "cardRarity" })
Filter by type: #Html.DropDownListFor(_item => _item.mType, Model.mTypeList, new { #id = "cardType" })
Filter by color: #Html.DropDownListFor(_item => _item.mColor, Model.mColorList, new { #id = "cardColor" })
</p>
<input type="submit" name="name" value=" " />
}
With the reference to the model class object (
#model MvcApplication7.Controllers.CardsFiltersViewModel
)

Categories