Using a paged list on model first approach? - visual-studio-2010

I would like to page the data in my view using a paged list , I did this previously using a web grid but am finding it difficult to do this using the model first approach.Any help would be much appreciated.
Thanks

Steve Sanderson describes an example of pagination support in his book Pro ASP.NET MVC 3 which I highly recommend (although it shouldn't be long until the next version is released).
He describes a product controller (listing pages of products) as:
public class ProductController : Controller {
public int PageSize = 4; //This could be retrieved from the database
private IProductRepository repository;
public ProductController(IProductRepository repoParam) {
repository = repoParam;
}
public ViewResult List(int page = 1) {
ProductsListViewModel viewModel = new ProductsListViewModel {
Products = repository.Products
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
return View(viewModel);
}
A query to the action may then be in the form:
http://localhost:23081/Product/List?page=2
(or whatever routing you require).
This view model would then be:
public class ProductsListViewModel {
public IEnumerable<Product> Products { get; set; }
public PagingInfo PagingInfo { get; set; }
}
And the PagingInfo model would be:
public class PagingInfo {
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public int TotalPages {
get { return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage); }
}
}
You can then use this paging information to display the information in your view as required.

Check out my PagedList nuget package on github:
https://github.com/troygoode/pagedlist
This will allow you to write code like so:
MyController.cs
public class MyController : Controller{
public object MyRoute(){
var pagedProducts = ProductsRepo.All().ToPagedList();
return View(pagedProducts);
}
}
MyRoute.cshtml
<ul>
#foreach(var product in ViewModel){
<li>#product.Name</li>
}
</ul>
#Html.PagedListPager(ViewModel, page=> Url.Action("MyRoute", {page = page}))

Related

more models on a mvc3 page

Could I have more models on a razor page?
for example when I have more grid controls each with an area(a template) for editing the data,and after that i want to save the data and see it in the grid.
You can do something like the example below (this is a very over simplified example):
public class AnimalDataViewModel
{
public List<Dog> DogData { get; set; }
public List<Cat> CatData { get; set; }
public List<Mouse> MouseData { get; set; }
public AnimalDataViewModel()
{
this.DogData = new List<Dog>();
this.CatData = new List<Cat>();
this.MouseData = new List<Mouse>();
}
}
Then in your action method:
public ActionResult DisplayAnimalDataGrids()
{
AnimalDataViewModel model = new AnimalDataViewModel();
model.DogData = this.myDataService.GetDogData();
model.CatData = this.myDataService.GetCatData();
model.MouseData = this.myDataService.GetMouseData();
return View(model);
}
Then in your view:
#model AnimalDataViewModel
#Html.Grid(Model.DogData)
#Html.Grid(Model.CatData)
#Html.Grid(Model.MouseData)

Proplem view category in mvc 3

I have 1 project name MVC1
I have 2 classes below:
public class category
{
public int ID {get;set;}
public string Name {get;set;}
}
public class detail
{
public int Id {get;set;}
public string Name {get;set;}
public int CategoryID{get;set;}
}
and 2 Intefaces
public inteface ICategory
{
IList<category> ListCategory();
}
public interface IDetail
{
IList<Detail> ListDetail();
}
and 1 Model RCateory inheritance from inteface ICategory
public IList<Category> FindAllCategory()
{
List<Category> Listcategory_ = new List<Category>();
foreach (var category in Listcategory)
{
Listcategory_.Add(category);
}
return Listcategory_;
}
and 1 Model name RDetail inheritance from inteface IDetail
public IList<Detail> FindAllDetail()
{
List<Detail> Listdetail_ = new List<Detail>();
foreach (var detail in Listdetail_)
{
Listdetail_.Add(detail);
}
return Listdetail_;
}
and 1 Controller
DetailController
private RDetail rDetail = new RDetail();
private RCategory rCategory = new RCategory();
public ActionResult ListDetail()
{
var detail = rdDetail;
return View("CreateDetail");
}
and 1 View type (cshtml) CreateDetail container
#model MVC1.Detail
How do I put into the category to #Html.DropDownListFor
As always in an ASP.NET MVC application you start by creating a view model class that will contain everything that your view needs:
public class MyViewModel
{
public Detail Detail { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
and then have your controller action populate and pass this view model to the view:
public ActionResult ListDetail()
{
var model = new MyViewModel();
model.Detail = rDetail;
model.Categories = FindAllCategory().Select(x =>
Value = x.ID.ToString(),
Text = x.Name
);
return View("CreateDetail", model);
}
and finally your view will become strongly typed to the view model and you will be able to display the dropdown:
#model MyViewModel
...
#Html.DropDownListFor(x => x.Detail.CategoryID, Model.Categories)

how to bind a dropdownlist to model properly to be able to pass values back from view to controller

I am trying to update a compound page model which as one of its properties has a list of objects.
My Model looks like this:
public class PageViewModel
{
public ProgramListVM ProgramsDDL { get; set; }
public PageViewModel()
{
this.ProgramsDDL = new ProgramListVM();
}
}
The ProgramListVM class is:
public class ProgramListVM
{
public List<ProgramVM> Program_List { get; set; }
public int SelectedValue { get; set; }
public ProgramListVM()
{
this.Program_List = new List<ProgramVM>();
this.SelectedValue = 0;
}
}
and ProgramVM is:
public class ProgramVM
{
public int ProgramID { get; set; }
public string ProgramDesc { get; set; }
public ProgramVM(int id, string code)
{
this.ProgramID = id;
this.ProgramDesc = code;
}
}
I try to render this dropdownlist by the following two:
1-
<%: Html.DropDownList("ProgramsDDL", new SelectList(Model.Page6VM.ProgramsDDL.Program_List, "ProgramID", "ProgramDesc", Model.Page6VM.ProgramsDDL.SelectedValue))%>
2-
<%: Html.DropDownListFor(m => m.Page6VM.ProgramsDDL.Program_List, new SelectList(Model.Page6VM.ProgramsDDL.Program_List, "ProgramID", "ProgramDesc"), Model.Page6VM.ProgramsDDL.SelectedValue)%>
But when I try to update my model through a controller action
[HttpPost]
public ActionResult UpdateUser(PageViewModel model)
{
}
model.ProgramsDDL.count is zero.
What is the best way to render this dropdownlist and be able to set the selected index, and also be able to send the selected index back to the controller?
You mixed up the parameters for Html.DropDownListFor(). Code sample below should work.
<%: Html.DropDownListFor(m => m.SelectedValue,
new SelectList(Model.Page6VM.ProgramsDDL.Program_List, "ProgramID", "ProgramDesc"),
null) %>
You also should have a SelectedValue in your model that's posted back.
public class PageViewModel
{
public ProgramListVM ProgramsDDL { get; set; }
public int SelectedValue { get; set; }
public PageViewModel()
{
this.ProgramsDDL = new ProgramListVM();
}
}
Also default model binder can't map complex collections to your model. You probably don't need them in your post action anyway.

html.dropdownlistfor() troubles...getting null reference exceptions

I've tried to follow a few examples from here and a couple other resources to just create a very simple member in my viewmodel and display it as a dropdown list on my view with a dropdownlistfor() helper. I can't seem to wrap my head around it and it's not working with what I'm trying.
here's my viewmodel:
public class Car
{
public int CarId { get; set; }
public string Name { get; set; }
}
public class MyViewModel
{
public IEnumerable<Car> Cars = new List<Car> {
new Car {
CarId = 1,
Name = "Volvo"
},
new Car {
CarId = 2,
Name = "Subaru"
}
};
public int MyCarId { get; set; }
}
and here is my view:
#Html.DropDownListFor(m => m.MyCarId, new SelectList(Model.Cars, "CarId", "Name"))
and here is my controller:
public ActionResult MyView()
{
return View();
}
You need to make sure you send the Model to your View:
public ActionResult Index()
{
var myViewModel = new MyViewModel()
return View(myViewModel);
}
And in your View you need to make sure you're defining your Model:
#model namespace.MyViewModel
You example works fine, I think you forgot to send MyViewModel in POST Action.
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}

Dropdownlist using LINQ/MVC3/C# problem getting it to bind

I am super new to MVC3 and C#, so excuse my noob questions. I have been struggling with this for almost a full day and hope someone can shed some light (I have scoured this site for clues, hints, answers as well).
I have a single table in my database which will hold all the data. It is for a profile editor which will store values that the user can populate their timekeeping entry form automatically upon select. I am on step one though, trying to populate the first dropdownlist with the profile name. I am using LINQ, MVC3/ Razer, and C#.
Here is my dbml:
Cant post image cause I am new
http://imageshack.us/photo/my-images/560/timem.png/
Here is my model:
namespace Timekeeping.Models
{
public class Profile
{
public int Profile_ID { get; set; }
public string profilename { get; set; }
public string networkuserid { get; set; }
public int projectnumber { get; set; }
public int costcode { get; set; }
public int paycode { get; set; }
public int jobtype { get; set; }
public int workorder { get; set; }
public int activity { get; set; }
public string taxarea { get; set; }
public IEnumerable<Profile> profiles { get; set; }
}
public class ProfileViewModel
{
public int Profile_ID { get; set; }
public IEnumerable<SelectListItem> profiles { get; set; }
}
}
Here is my Controller:
namespace Timekeeping.Controllers
public class TimeProfileController : Controller
{
private static String strConnString = ConfigurationManager.ConnectionStrings["timekeepingConnectionString"].ConnectionString;
[HttpGet]
public ActionResult ProfileSelect()
{
profileConnectionDataContext dataContext = new profileConnectionDataContext(strConnString);
var model = new ProfileViewModel();
var rsProfile = from fbs in dataContext.TimeProfiles select fbs;
ViewData["ProfileList"] = new SelectList(rsProfile, "Profile_ID", "profilename");
return View(model);
}
}
And here are all the different html helpers I have tried for my View(none work):
#Html.DropDownList("rsProfile", (SelectList)ViewData["ProfileList"]))
#Html.DropDownListFor(
x => x.Profile_ID,
new SelectList(Model.profiles, "Values", "Text"),
"-- Select--"
)
#Html.DropDownListFor(model => model.Profile_ID, Model.profilename)
I know this is a mess to look at, but I am hoping someone can help so I can get on with the hard parts. Thanks in advance for any help I get from the community
Hope it will work surely...
Inside Controller :
var lt = from result in db.Employees select new { result.EmpId, result.EmpName };
ViewData[ "courses" ] = new SelectList( lt, "EmpId", "EmpName" );
Inside View :
<%: Html.DropDownList("courses") %>
Try this:
public class TimeProfileController : Controller
{
private static String strConnString = ConfigurationManager.ConnectionStrings["timekeepingConnectionString"].ConnectionString;
[HttpGet]
public ActionResult ProfileSelect()
{
var dataContext = new profileConnectionDataContext(strConnString);
var profiles = dataContext.TimeProfiles.ToArray().Select(x => new SelectListItem
{
Value = x.Profile_ID,
Text = x.profilename
});
var model = new ProfileViewModel
{
profiles = profiles
};
return View(model);
}
}
and in the view:
#model ProfileViewModel
#Html.DropDownListFor(
x => x.Profile_ID,
new SelectList(Model.profiles, "Values", "Text"),
"-- Select--"
)
If you are using a model class just try this:
<%: Html.DropDownList("EmpId", new SelectList(Model, "EmpId", "EmpName")) %>
If you want to add click event for drop down list try this:
<%: Html.DropDownList("courses", ViewData["courses"] as SelectList, new { onchange = "redirect(this.value)" }) %>
In the above one redirect(this.value) is a JavaScript function

Resources