How to show the current user using ASP MVC and EF - c#

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;%>

Related

MVC Redirect not working properly

Hi I AM using Database first approach in my MVC project. I have an action where I am calling Stored procedure when user clicks on Accept terms.
Here as soon as i calling this stored procedure, in my table it is storing current date and making termsaccepted field from false to true. It is working fine. I have condition like only when user accepted terms they can redirect to Default page. But even after calling stored procedure and updating date it is not redirecting to Default page.
And what I observed is, if i close and open my solution, then it is taking latest value stored in database and then it is redirecting to page which i need.
So how can i redirect to page as soon as value updated in my database without restarting Visual Studio ?
My Action :
public ActionResult Termspage()
{
TermsEntities updateterms = new TermsEntities();
var ID = Session["userID"];
if (ID != null)
{
updateterms.usp_UpdateUserTerms(Convert.ToInt32(ID), true);
updateterms.SaveChanges();
}
return View();
}
My View :
<body>
<div>
#using (Html.BeginForm("DefaultPage", "Home", FormMethod.Post, new { id = "frmIndex" }))
{
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<input type="submit" value="Accept Terms & Condition" />
</td>
</tr>
</table>
}
</div>
</body>
Here it's not redirecting to Defaultpage action even after details are updated in my database. But when i reopen my solution then it is redirecting to Defaultpage.
Update :
I tried to use redirecttoAction but when I use this I am getting This webpage has redirect loop error
Try PostRedirectGet method in MVC using RedirectToAction
public ActionResult Termspage()
{
TermsEntities updateterms = new TermsEntities();
var ID = Session["userID"];
if (ID != null)
{
updateterms.usp_UpdateUserTerms(Convert.ToInt32(ID), true);
updateterms.SaveChanges();
return RedirectToAction("Detail", new {id=ID})
}
}
Then
public ActionResult Detail(int id)
{
// get record
return View();
}

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.

HowTo: Using MvcContrib.Pagination without using MvcContrib.Grid View

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
:)

C# How to set the autopostback property when using asp.net mvc?

I am using asp.net MVC framework. On my page i have a dropdwonbox and when an option is clicked i want to go to another page. But i can't find how/where to set the autopostback property to true. This is the code i'm using:
Aspx:
<%= Html.DropDownList("qchap", new SelectList( (IEnumerable)ViewData["qchap"], "Id", "Title" )) %>
Controller:
public ActionResult Index(int id)
{
Chapter c = new Chapter();
ViewData["qchap"] = c.GetAllChaptersByManual(id);
return View();
}
What do i have to do to use the autopostback functionality?
You can use the onchange client event:
<%= Html.DropDownList("qchap",
new SelectList( (IEnumerable)ViewData["qchap"], "Id", "Title" ),
new { onchange = "this.form.submit();" }) %>
It seems the DropDownList helper method doesn't support this.
Maybe using it within a form and a custom custom html attribute to submit the form do it.
I believe too that you may want to adjust your postback to the formsCollection
postback public ActionResult Index(FormsCollection myform)
(I'm not on my home pc where MVC is installed, so I can't verify the syntax here)
I solve using this code.
Function Index(ByVal collectionField As FormCollection) As ActionResult
Dim industryCategoryID As Long = collectionField.Item("ddlIndustry")
If industryCategoryID = 0 Then
Me.ViewData("IndustryList") = GlobalController.GetIndustryList
Return View(_service.ListCompanies())
Else
Me.ViewData("IndustryList") = GlobalController.GetIndustryList
Return View(_service.ListCompanies(industryCategoryID))
End If
End Function
That's for the ActionResult function
And Then for the View
<p>
<% Using Html.BeginForm()%>
<%=Html.DropDownList("ddlIndustry", New SelectList(CType(ViewData("IndustryList"), IEnumerable), "ID", "Name"), "--Choose industry--", New With {.onchange = "this.form.submit()"})%>
<% End Using %>
</p>
I hope it helps. I f you would like more complete codes please feel good to email me at boylevantz#gmail.com

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