HowTo: Using MvcContrib.Pagination without using MvcContrib.Grid View - c#

This started as a question, but turned into a solution as I did some experimenting! So I thought I would share this with you all. My question WAS:
How to use MvcContrib.Pagination without using MvcContrib.Grid View?
My answer is below...

I am building a Help Desk Ticketing System (I am kind of a C# newbie - got many pointers from NerdDinner) and I wish to use some sort of paging library to help with the view. I found MvcContrib.Pagination and I got it to work for a view. My view does NOT use MvcContrib.Grid because it is custom.
Scaled down version of my view List.aspx :
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyProject.Areas.HelpDesk.Models.hd_Ticket>>" %>
<%# Import Namespace="MyProject.Areas.HelpDesk.Controllers" %>
<%# Import Namespace="MvcContrib.Pagination" %>
<h2>Help Desk Tickets (showing <%= Model.Count() %> of <%= ViewData["totalItems"] %>)</h2>
<% foreach (var item in Model) { %>
<h3><%= Html.Encode(item.Subject)%></h3>
<% } %>
<p><%= Html.Pager((IPagination)Model)%></p>
My controller (part) TicketController.cs :
TicketRepository ticketRepository = new TicketRepository();
public ActionResult List(int? page, int? pageSize)
{
IPagination<hd_Ticket> tickets = null;
int dPageSize = 50;
int totalItems;
tickets = ticketRepository.GetTickets().ToList().AsPagination(page ?? 1, pageSize ?? dPageSize);
ViewData["totalItems"] = tickets.TotalItems;
return View("List", tickets);
}
I am using the repository pattern which is returning the results as IQueryable. Here is part of the TicketRepository.cs file:
public class TicketRepository
{
private HelpDeskDataContext db = new HelpDeskDataContext();
public IQueryable<hd_Ticket> FindAllTickets()
{
return from ticket in db.hd_Tickets
orderby ticket.CreatedDate descending
select ticket;
}
}
All this may be trivial to some, but if someone like me is trying to learn C# and ASP.NET MVC and paging, then this may be useful. I recommend newbies to do the NerdDinner tutorial found at:
http://nerddinnerbook.s3.amazonaws.com/Intro.htm
:)

Related

How to show the current user using ASP MVC and EF

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005. I am using also Entity Framework with Code First Method.
I have an interface for the LOG ON (connection) which it is related to my base where i have a USER table (contain Login + password).
I am just want to show the Current User which is logged. So, I created a ViewModel Class for the User but i didn't get any result.
This is what I tried to do in my Controller :
public ActionResult LogOn()
{
var user = new UserViewModel();
user.Nom_User = this.User.Identity.Name;
ViewData["UserDetails"] = user;
return View();
}
and this what I add in the master page :
<% var User = ViewData["UserDetails"] as MvcApplication2.ViewModels.UserViewModel; %>
Hello : <%: User.Nom_User %>!
When I execute, I have this error :
Object reference not set to an instance of an object.
You said that you placed this code in your MasterPage. This means that it will run for every view.
But you have set the ViewData["UserDetails"] only inside the LogOn action. So when you navigate to some other action (such as the Home/Index action for example) it will bomb because there's nothing inside this ViewData["UserDetails"] and of course this User variable which you declared in your MasterPage will be null.
I would recommend you using a child action for that.
[ChildActionOnly]
public ActionResult LogedInUser()
{
if (!Request.IsAuthenticated)
{
return PartialView();
}
var user = new UserViewModel();
user.Nom_User = User.Identity.Name;
return PartialView(user);
}
and in your MasterPage:
<% Html.RenderAction("LogedInUser", "Account"); %>
or if you prefer:
<%= Html.Action("LogedInUser", "Account") %>
And finally you could have the corresponding LogedInUser.ascx partial that will be strongly typed to your view model:
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<UserViewModel>"
%>
<% if (Model != null) { %>
<div>Hello : <%= Html.DisplayFor(x => x.Nom_User) %></div>
<% } %>
Phil Haack blogged about child actions in more details here.
Try using session
Session["user"]=this.User.Identity.Name;
and in view you can get user name with <% var User =Session["user"]%> or you can directly use:
<% var User =this.User.Identity.Name;%>

Posting two and more lists in asp.net mvc

I'm using asp.net mvc 2 and i found this behavour which i can't understand.I have following view:
<% using (Html.BeginForm("Index", "BlackListGrabber", FormMethod.Post) )
{
<%= Html.DropDownListFor(m => m.selectedArea, new SelectList(Model.areaList, "value", "text")) %>
<% if (Model.districtList != null) { %>
<%= Html.DropDownListFor(m => m.selectedDistrict, new SelectList(Model.districtList, "value", "text")) %>
<% } %>
<% if (Model.townList!= null) { %>
<%= Html.DropDownListFor(m => m.selectedTown, new SelectList(Model.townList, "value", "text")) %>
<% } %>
<input type="submit" value="post" />
<% } %>
and a controller's method like this:
[HttpPost]
public ActionResult Index(BlackListGrabberModel postedModel)
{
BlackListGrabberModel model = new BlackListGrabberModel(postedModel);
return View(model);
}
And, last but not least, my model:
BlackListGrabberModel(BlackListGrabberModel model)
{
if (string.IsNullOrEmpty(model.selectedArea))
{
areaList = GetRegions();
}
else if (string.IsNullOrEmpty(model.selectedDistrict))
{
areaList = model.areaList;
districtList = GetRegions(model.selectedArea);
}
else if (string.IsNullOrEmpty(model.selectedTown))
{
areaList = model.areaList;
districtList = model.districList;
districtList = GetRegions(model.selectedDistrict);
}
}
Idea is that then i load page, i see list of all possible areas.(And i see it - it's my first dropdownlistfor) When i select area, after clicking "post" button, i see list of all districts, they loaded from external source and this part works fine.
So i select district from list, and click "post". After thar i see list of all towns located in selected district, but districtList disappears. Then i traced it in my controller, i found that property postedModel.districtList is null. But postedModel.areaList is fine! Does that mean that i can post only one SelectList, or i'm missing something? Can somebody please give me any help?
P.S. Properties "selectedArea", "selectedDistrict", "selectedTown" are posted as expected.
EDIT. Thanks to everybody, i missed some important things, and you gave me direction to them.
My problem appeared to be areaList. It was filled by default constructor. I forgot about that, so then i saw postedModel.areaList filled, i thought it was magically posted by asp.net mvc mechanisms, and complained that all other lists are not filled because of some strange glithces.
You will have to repopulate your list properties in your model for every request.
The won't get posted back automatically. Just the selected value is posted back and bound to the property in your model (i.e. selectedArea is bound but not areaList).
The lists should not post, only the values of the select elements in your html form will. If you need to hold onto the list values, you might try placing them in TempData in you GET for Index, which will keep them for the next request.

Generating HTML from server-side block in ASP.NET MVC

This is a very newbie kind of ASP.NET question: I simply don't know and can't work out the correct syntax to use.
In my view I want to generate an action link if a certain condition is true on my model. I know how to generate a link using this syntax:
<%: Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID }) %>
But for some reason that syntax doesn't work in this code:
<%
if (Model.CanDoSomething)
Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID });
%>
I really am a newbie to ASP.NET, so I don't even know what the semantic name is for the different syntaxes <% and <%:; all I can tell is that <% is to void as <%: is to string. And clearly executing a line of code that just returns a string (Html.ActionLink()) is not going to have any effect. But what, pray what is the correct method to make my page render the action link?
It's a great pity I can't Google on "<%"! Any links or explanations of this subject will also be much appreciated.
This will do the trick
<% if (Model.CanDoSomething) { %>
<%: Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID }) %>
<% } %>
<%: writes to the output buffer but encodes the string. You could also use <%= for unencoded output because ActionLink returns an encoded MvcHtmlString.
EDIT: This may also work
<%
if (Model.CanDoSomething)
Response.Write(Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID }));
%>
<% - this by itself has no output. You would include code with no output in this block such as an if statement. If you want output - you must use it in conjunction with <%=
The difference with the : is that
<%: means it will output to the response stream, not = required however the : means the output will be htmlencoded.
<%:"sometest&text" %> //will emit "sometesttext" on the page.. htmlencoded.
<%="sometest&text" %> //will give you the same result without the '&' htmlencoded
<% SomeFunction() %> //will just run that function - there is no output
//you want
<%if (Model.CanDoSomething){%>
<%:Html.ActionLink("Do Something", "DoSomething", new { id = Model.ID })%>
<%}%>

MVC Entity Framework using a nested foreach in view

I'm passing 3 sets of data through to a view in a viewmodel and have a problem relating one of them to the other two in my foreach coding:
My DB tables are:
"ServiceGroups" is parent to "Services"
"Services" is related through a joining table (using a 2 composite Primary Key) to the aspnet_users table (I call "Users")
I pulled this into an EF model called GWServices.edmx
so now I have 3 entities related like so:
ServiceGroup (parent to) Service
Service (many to many with) User
Then I created a controller and a viewmodel like this:
{
public class ServicesViewModel
{
public ServicesViewModel(List<ServiceGroup> servicegroups, List<Service> services, List<User> aspnetusers)
{
this.ServiceGroups = servicegroups;
this.Service = services;
this.AspnetUsers = aspnetusers;
}
public List<ServiceGroup> ServiceGroups { get; set; }
public List<Service> Service { get; set; }
public List<User> AspnetUsers { get; set; }
}
public class ClientServicesController : Controller
{
public ActionResult Index()
{
GWEntities _db = new GWEntities();
var servicegroups = _db.ServiceGroupSet.ToList();
var services = _db.ServiceSet.ToList();
var aspnetusers = _db.UserSet.ToList();
return View(new ServicesViewModel(servicegroups, services, aspnetusers));
}
}
}
Next I created the view with 3 foreach loops to:
Get and present as a UL, a list of all service groups in the database (which worked)
Populate a table under each Servicegroup filling down some Service data for each Service within that given group (which also work)
Test whether the user is associated with this particular Service, if so show only the red cross icon, otherwise show the green "select me" icon. (this doesn't populate any users)
So the code looks like this:
<% foreach (var servgroup in Model.ServiceGroups) { %>
<ul> <%= servgroup.ServiceGroupName%> </ul>
<table>
<% foreach (var serv in servgroup.Service)
{ %>
<tr>
<td class="td1">
<%= serv.ServiceDescription%>
</td>
<td class="td2">
<% = Html.Encode(String.Format("{0:f}",serv.MonthlyPrice)) %>
</td>
<td class="td3">
<%foreach (var user in serv.User) {%>
<%if (user.UserName == User.Identity.Name)
{ %>
<img src="/Content/LightRedCross_2.png" alt="" height="15px" width="15px"/>
<% }
else
{%>
<img src="/Content/LightGreenAdd_2.png" alt="" height="15px" width="15px"/>
<%} %>
<%} %>
</td>
</tr>
<% } %>
</table>
<% } %>
Can anyone tell me why foreach(var user in serv.user) does not recognise that "Customer1" (the currently logged in user) has 6 services ordered (as it is in the joining table)?
Thanks!
Paul
Looking at your code I think this could be resolved by loading the child tables of ServiceGroups.
It is likely that the Services & User reference was not loaded in the original Entity Framework query. Therefore, as you are trying to iterate through the children in the foreach loop, it does not see a collection, it just sees null.
You should try altering your retrieval statements:
_db.ServiceGroupSet.ToList()
to
_db.ServiceGroupSet.Include("ServiceSet").Include("UserSet").ToList()
If this doesn't fix your issue, I would put a break point on the below line of code and traverse the List to see if it has the data you expect.
this.ServiceGroups = servicegroups;
For starters, username comparisons are generally case-insensitive. So this:
<%if (user.UserName == User.Identity.Name)
...should be:
<%if (user.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase))
You also have a bug where you don't dispose your entity context. You should override Controller.Dispose and dispose it there. This allows the view to render before the context is disposed.

Display list of available Roles from DB as checkboxes like NerdDinner does with Countries

I have an ASP.NET MVC project in C# using Forms Authentication and Active Directory is the Membership Provider (users login with their existing uid/pwd). However, I would like the roles to be supplied by aspnet_Roles (the default table created by the application). In my Web.config I have: with default setting for this node.
I successfully followed the NerdDinner sample application PDF and wish to use what I have learned. In my app I am using the Repository pattern just like NerdDinner. In NerdDinner, it shows how to use a Helper method to populate a DropDownList. I would like to do the same, but instead of countries and DropDown I would like to pull Roles from a table and populate check boxes.
In my UsersController.cs I have:
//
// ViewModel Classes
public class UserFormViewModel
{
// properties
public User User { get; private set; }
public SelectList Roles { get; private set; }
// Constructor
public UserFormViewModel(User user)
{
User = user;
Roles = new SelectList(Roles.All, ); //this is where I have problems
}
}
In my view I have (which of course will not work):
<ul>
<% foreach (var role in Roles as IEnumerable<SelectListItem>)) { %>
<li><%= Html.CheckBox(role.ToString())%> <%= role.ToString() %></li>
<% } %>
</ul>
P.S. I am a newbie to .NET, but I love it! Correct me if I am wrong, but I think this issue has to do with collections and type definitions?
Also, I am familiar with using the ASP.NET configuration tool to add Roles and Users, but I would like to create a custom User Admin section.
Something like this ?
<li><%= Html.CheckBox(role.ToString(),
Roles.IsUserInRole(Model.User.Identity.LoginName, role.ToString())) %>
<%= role.ToString() %>
</li>
Cant quite remember the exact syntax of the Roles in the asp.net membership provider, but it is something along those lines.
It looks like I do not need use the UserFormViewModel class. Morph helped me out. This is what I am doing:
<ul>
<%
string[] allroles = Roles.GetAllRoles();
foreach (string role in allroles) {
%>
<li>
<%= Html.CheckBox(role.ToString(), Roles.IsUserInRole(Model.UserName, role.ToString())) %>
<%= role.ToString() %>
</li>
<% } %>
</ul>

Categories

Resources