RedirectToAction redirecting to wrong User ID - c#

Edit: I am still encountering this issue but I have solved it displaying the applications on 2 users profile instead of the user that created it. I am still running into the issue of redirecting to the wrong ID however and I can't find any information online about it. All the breakpoints up to the redirect point to the correct ID so I am really perplexed. As stated below, I had altered my viewbag and variables to be consistent and it did not fix the issue.
I have an application that allows users to add applications to their profile. Their profile will list all of the applications made by that user. The application has been configured in the RouteConfig file to initialise the application in the profile of UserId 1.
What is happening is that if I create an application for UserId 1, it works fine, adds the application to the list of applications for UserId 1 and displays it. If I create a new user (UserId 2) and then proceed to add a new application for that user, the redirect action that happens when the application is submitted to the database takes me back to UserId 1's page with the application being added to UserId 1's list and also to the UserId that created it (In this instance, UserId 2). I'm not sure why this is happening as I am explicitly telling it to get the UserId from the ViewBag that is storing the correct UserId.
If I look into the database, there is only 1 record for the application. I can delete the application in UserId 1's list and it will still exist in UserId 2's list and also the database. If I remove it through the UserId 2's page, it will remove the record from all lists and database. This also applies to updating the details of the application.
When I've set a breakpoint at the very end where the controller will pick up the UserId and then redirect me to that UserId's page. It states the correct UserId's page it needs to redirect to (In the scenario above, it states the UserId is 2). However, as already stated, it is redirecting me to the UserId 1.
If I remove the route in the RouteConfig file that initialises the application in UserId 1 and just load up the default index page, create a user then create an application, I am given an error stating System.NullReferenceException because I'm trying to display the name of the user using - <h2>User Profile for #Model.Name</h2> so it's not picking up the details of the UserId. I'm not sure why this is happening either as I thought the RouteConfig file was purely to tell the application where to inialise.
Code below, some points to make:
This is what the URL looks like when I am about to submit the application = https://localhost:44313/Service/AddApplication?Course=Level1&DriverId=1&UserId=2
RoutesConfig is sending to "GetUser", "User", 1 at application start
The viewbags are working as I can see that it picks up the correct UserId at the very end of the adding process.
Controller Action to Add Application;
[HttpPost]
public ActionResult AddNewApplication(ApplicationAdd applicationAdd, string UserId, int DriverId)
{
try
{
// TODO: Add insert logic here
applicationService.AddApplication(applicationAdd, UserId, DriverId);
return RedirectToAction("GetUser", "User", new { UserId = ViewBag.UserId });
}
catch
{
return View();
}
}
GetUser action in User Controller:
public ActionResult GetUser(string id)
{
return View(userService.GetUser(id));
}
GetUser action in userService:
public User GetUser(string id)
{
using (var context = new MyContext())
{
return userDAO.GetUser(id, context);
}
}
GetUser in userDAO:
public User GetUser(string id, MyContext context)
{
context.Users.Include(g => g.Applications).ToList();
return context.Users.Find(id);
}
RouteConfig file path:
defaults: new { controller = "User", action = "GetUser", id = 1 }
Controller Action that is giving the view to display the list of applications for a user:
public ActionResult GetApplications(string id)
{
User user = userService.GetUser(id);
IList<Application> applications = user.Applications.ToList();
return View(applications);
}

Try using this
RedirectToAction("GetUser", "User", new { id = ViewBag.UserId });
the parameter name UserId needs to be the same as the one in the funcation id.

Related

login form not submitting after adding new fields to table .net mvc

I added 1 new field to my table, added the field to Model DTO and Model ViewModel cs, but Login form submit seems to be not working post that.
There is no error showing, login page simply refreshes. Steps I took are as follows
1) New field added manually to the Table
2) Added new field to the Model DTO and Model ViewModel cs
[HttpPost]
public ActionResult Login(UserVM model)
{
if(ModelState.IsValid)
{
using (Db db = new Db())
{
var user = db.User.Where(x => x.Username.Equals(model.Username) && x.Password.Equals(model.Password)).FirstOrDefault();
if(user != null)
{
Session["Id"] = user.Id.ToString();
Session["Username"] = user.Username.ToString();
Session["Password"] = user.Password.ToString();
Session["Firstname"] = user.Firstname.ToString(); //NewField
Session["RoleName"] = user.RoleName.ToString();
return RedirectToAction("UserProfile");
}
else
{
ModelState.AddModelError("", "Username / Password is Invalid");
return View(model);
}
}
}
return View();
}
Ok, I was able fix this by myself. Issue here I noticed was very unique, And i will be glad to explain from start.
I created a table with this info first
Id, Username, Password.
Then created its Action in Controller, and all was set to work.
Later I decided to add new fields to table, say Firstname, Lastname and Email.
Now, here is where the problem came. In Model ViewModel I had created a Model Class as UserVM, So, if I add these new properties to ModelClass with [Required] data annotaion, only then the Login Action does not respond. Action works if I go back and remove [Required] Data annotation.
I did google this to see a solution but no success.
For now Closing this ticket as resolved, but would love to know how can we make the Action run with [Required] data annotation added on the new fields in the Model Class.

Registration Admin Approval verification in C# asp dot net MVC

I need "admin approval" for login as user after the registration. I am doing it in asp.net MVC, using ms sql, visual studio. I am new to it,need help badly, how many way I can do it and whats the process to do that.
My thought: I made login Registration with email verify. Now I need to make admin verify.
Here is my database table :
Database: I made a registration table(Tbl_User), Approval Table(Tbl_Approval). I need to confirm admin approval while login:
var approval = dc.Tbl_Approval.Where(m => m.Tbl_User.EmailID == login.EmailID).FirstOrDefault();
if (!approval.ApprovalStatus)
{
ViewBag.Message = "Please wait for admin approval";
return View();
}
For this I need to insert the Tbl_User data into Tbl_Approval table which is previously empty. so I need the query in the controller action(for Tbl_Approval) to get the (Tbl_User)list into Tbl_Approval table and edit the Approval status. I tried this:-
public ActionResult List()
{
List<Tbl_User> userList = db.Tbl_User.ToList();
Tbl_Approval approval = new Tbl_Approval();
List<Tbl_Approval> approvalUserList = userList.Select(x => new Tbl_Approval { UserID = x.UserID }).ToList();
return View(approvalUserList);
}
Please help me on the controller action to get the(Tbl_User) list into the Tbl_Approval table. Also suggest me any other good way to do this task.
You can create the Action method for approval process. When admin approves any particular user, you need to pass that userId. I have used EntityFramework for the example.
Here is the code that should work
public ActionResult ApproveUser(int userId)
{
var user = context.Users.Find(userId);
if(user != null)
{
user.ApproveStatus = 1;
context.Entry(user).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
return View();
}
TO solve this issue do the following i.e.
Add the status column in your login table and set the default approval status for all new sign ups as not approved.
Create a module for admin only in your web portal to view/approve the new sign ups.
Create designated actions with view pages in your new module to view and approve the signups.
I recommend creating a new controller for this new module that is accessible to the admin only and not to everyone else.
When the admin login the system show notifications to him so, he can open and go to this new module and perform approval actions.
When the admin performs the approval action update the approval status from not approve to approve.

ASP.Net Core MVC - Auth Context different for partial views?

I have a Model that produces 2 partial views.
One partial view contains a form to change your username
The other contains a form to change your password
Both forms reach back to a POST method in the UserController. Each section, independently works fine. However, if I change the username and then try to change the password, the Auth Context contains the old username and I encounter an error.
The logic goes a little like this...
Change Username
Controller
public async Task<ActionResult> ChangeUsername(ChangeUsernameViewModel model) {
string oldUsername = model.OldUsername;
string newUsername = model.NewUsername;
User user = await this.UserService.GetUserById(this.Authorization.UserId);
if (user != null)
{
// Update username in DB
User user = await this.UserService.ChangeUsername(user, newUsername);
// Update cookie
this._owinContext.Authentication.SignIn(this.Authorization.ToClaimsIdentity());
// Update ViewModel
model.OldUsername = newUsername;
model.NewUsername = string.Empty();
}
return View(model);
}
Service
public async Task<User> ChangeUsername(User user, string newUsername) {
// Blah blah blah... Code to update user with new username
// and save changes to DB which is then followed by:
// Change claim in Auth Context
this._authorization.RemoveValue(MyClaimType.Username);
this._authorization.AddValue(MyClaimType.Username, newUsername);
// At this point, I can see that the Auth Context
// has been updated with the new username.
return user;
}
Change Password
Controller
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model) {
string oldPassword = model.oldPassword;
string newPassword = model.newPassword;
User user = await UserService.GetUserByLogin(this.Authorization.Username, oldPassword);
// this is where the failure occurs, so I won't
// bother writing out the rest.
// this.Authorization.Username is equal to "oldUsername"
// that we saw in the ChangeUsername method.
}
Does this._authorization in the service not carry back over to this.Authorization the controller?
Is this.Authorization different for each partial view for some reason?
Clear/Reset/logout the user session, Reload the session data info with the new data supplied by the user or from db

How do I get current user another property asp mvc 5

I have a situation.
AspNetUsers has a column called AccType which is int type
If AccType is 1 = customer
If AccType is 2 = manager.
I can access to current logged user id by User.Identity.GetUserId()
I am trying to do if statment as following:
if(User.Identity.GetUserId().AccType == 1){
redirect to specific page..
}elseif (User.Identity.GetUSerId().AccType == 2){
redirect to 2nd specific page..
}
User.Identity.GetUserId().AccType this is now working.
Please help! Thanks!
User.Identity.GetUserId() returns the id of the currently logged in user. However, if you want to access its properties, you need to get the actual user object. One way to to this is the following:
var userId = this.User.Identity.GetUserId();
var user = this.Request.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(userId);
A more convenient way will be to make a property for the ApplicationUser in your controller and then to reuse the code.
Property:
public ApplicationUserManager UserManager
{
get
{
return this.Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
}
Getting the user:
var user = this.UserManager
.FindById(this.User.Identity.GetUserId());

Multiple role based registration in mvc4 c# aspx

I have 5 roles of users.They are Admin,Distributor,Micro-distributor,Dealer and User.Admin has the privilege of accessing all pages of other user and all CRUD operations on it.All these users have different fields from others.If dealer register his details then the values stored into a register table in SQL server database.this is same for all roles.basic details of all users columns are same.but other details like bank details and shop details are extra columns of distributors and dealers.So you can store the registration details to one column or different columns.but user can login to their account based on their roles,that is if a dealer tries to login,then server must check such a dealer exist in the database.If yes then he redirect to his profile page.I need the complete model view and controller source code for this problem in mvc4 or mvc3.you canuse the sql server database for this action...
I use the following code snippet for login action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogon u)
{
if (ModelState.IsValid)
{
using (TranzEntities2 dc = new TranzEntities2())
{
var v = dc.tbl_User.Where(a => a.user_name.Equals(u.user_name) && a.password.Equals(u.password)).FirstOrDefault();
if (v != null)
{
Session["LogedUserID"] = v.user_id.ToString();
Session["LogedUserFullname"] = v.first_name.ToString();
return RedirectToAction("Home");
}
else
{
ModelState.AddModelError("Error", "Login failed, Try again");
}
}
}
return View(u);
}
But it is for only one table.I need to check the user login based on their roles.Suppose if someone try to login then it automatically check the user belongs to which table.if he belongs to a dealer table then dealer page will redirect after login success.

Categories

Resources