delete a user based on id from my databse context - asp.net-mvc

I am trying to implement the basic delete action method for a user:
private User_Manager_Interface.Models.ApplicationDbContext userDb = new User_Manager_Interface.Models.ApplicationDbContext();
// POST: /Users/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
//.Remove(u => u.id == id);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I am not entirely sure how to delete a user.
This is what I have tried so far:
userDb.Users.Remove(); But now I don't know how to tell it to delete the user with a certain ID?
How do I do this?

Assuming that your userDb is DbContext (not an ObjectContext) there are a few ways to achieve your goal.
You can do this in the following way:
var user = userDb.Users.FirstOrDefault(u => u.UserId == id);
if(user != null)
{
userDb.Users.Remove(user);
}
Or you could do this:
var user = userDb.Users.FirstOrDefault(u => u.UserId == id);
if(user != null)
{
userDb.Entry(user).State= EntityState.Deleted;
userDb.SaveChanges();
}

Check out this tutorial - Remove Entity in Entity Framework
Sample code from tutorial -
using (var dbCtx = new SchoolDBEntities())
{
//if already loaded in existing DBContext then use Set().Remove(entity) to delete it.
var newtchr = dbCtx.Teachers.Where(t => t.TeacherName == "New teacher4")
.FirstOrDefault<Teacher>();
dbCtx.Set(Teacher).Remove(newtchr);
//Also, you can mark an entity as deleted
//dbCtx.Entry(tchr).State = System.Data.EntityState.Deleted;
//if not loaded in existing DBContext then use following.
//dbCtx.Teachers.Remove(newtchr);
dbCtx.SaveChanges();
}

Related

MVC Display data based on users login

I have this table where displaying the list of userID+SubjectID, now i want is,if the user who Logged in can only see the list of Subject that belongs to the current user,is it possible? then should i need to use asp.net identity? currently i am using empty template with custom login Authentication + Roles only, any idea on what is the best way to handle this type of scenario? all i want is my tables will show data based on the current user logged in.
Example: If User1 logged in then User1 will only see subjects belong to user1..
Note:
i was searching for tutorials on showing data based on the current user logged in, but i couldn't find,any one has better idea? or link can share with me? i don't know the better word for my scenario i just call it "show data based on current user",i appreciate if anyone can solve this..thanks in advance..
Table Controller:
[CostumAuthorize(Roles = "Admin,Teacher")]
public ActionResult Subject_List(int id)
{
var test = db.SubjectTeachers.Where(x => x.Users.Any(n => n.UserID == id)).ToList();
var subjectTeachers = db.SubjectTeachers.Include(s => s.Levels).Include(s => s.Subjects).Include(s => s.Users).Where(u => u.LevelID == id);
return View(subjectTeachers.ToList());
}
Account controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login l, string ReturnUrl = "")
{
if (!ModelState.IsValid)
{
return View(l);
}
using (MyContext dc = new MyContext())
{
var user = dc.Users.Where(a => a.Username.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.Username, l.RememberMe);
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "Invalid Login.");
return View(l);
}
[Authorize]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
}
If you can get the logged-in userid then simply use that to get Corresponding Subjects list.........
int userid = Membership.GetUser(User.Identity.Name).ProviderUserKey;
[CostumAuthorize(Roles = "Admin,Teacher")]
public ActionResult Subject_List()
{
var test = db.SubjectTeachers.Where(x => x.Users.Any(n => n.UserID == userid )).ToList();
return View(test.ToList());
}

Remove User from Roles in ASP.NET Identity 2.x

How can I remove User from Roles in ASP.NET Identity 2.x ?
about adding role to user there is no problem but when I want to remove a role from a user I cannot.It should be mentioned that there is no exception or error!
//POST: Admin/User/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Prefix = "")]UserViewModel userViewModel, List<int> availableRoles)
{
if (ModelState.IsValid)
{
List<int> newListOfRolesIDs = availableRoles;
List<int> oldListOfRolesIDs = UserBLL.Instance.GetRolesIDs(userViewModel.Id);
List<int> deletedList;
List<int> addedList;
var haschanged = oldListOfRolesIDs.ChangeTracking(newListOfRolesIDs, out deletedList, out addedList);
using (new EFUnitOfWorkFactory().Create())
{
if (haschanged)
{
UserBLL.Instance.InsertRoles(addedList, userViewModel.Id);
UserBLL.Instance.DeleteRoles(deletedList, userViewModel.Id);
}
await UserBLL.Instance.UpdateAsync(userViewModel);
}
//ArticleBLL.Instance.UpdatePartial(articleViewModel, m => m.Title);
return RedirectToAction("Edit");
}
return View(userViewModel);
}
Delete Role method:
public void DeleteRoles(List<int> deleteList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in deleteList)
{
user.Roles.Remove(new UserRole { RoleId = i, UserId = user.Id }); // What's the problem?!
}
}
}
Insert Role method:
public void InsertRoles(List<int> insertList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in insertList)
{
user.Roles.Add(new UserRole { RoleId = i, UserId = user.Id });
}
}
}
What you are looking for is the RemoveFromRoleAsync method. An example would look similar to the following:
public async Task DeleteRolesAsync(List<string> deleteList, int? userId)
{
if (userId != null)
{
foreach (var roleName in deleteList)
{
IdentityResult deletionResult = await UserManager.RemoveFromRoleAsync(userId, roleName);
}
}
}
If you already have the ID of the user, there's no need to get the user again (only if you want to make sure that the user really exists; then you have to wrap your foreach with an if-statement). The deletion methods needs the name of the role, instead of the ID, to delete the user from the role. You can use the result of the operation (in my example stored in deletionResult) to make sure that the operation was successful. Remember that the name of the user manager (in my example UserManager) can vary depending on your implementation.
I had the same issue and what I ended up using was the
RemoveFromRolesAsync(string userId, params string[] roles) Method
from the UserManager.
Using the role names in an array works.
But has an issue that is if the user is not in one of the roles in the array the user will not be removed from any roles in the array.
All or nothing.
var usr = UserManager.FindById(usrV.ID.ToString());
string[] deleteList;
deleteList= new string[1];
deleteList[0] = "Engineer";
var rresult1 = UserManager.RemoveFromRolesAsync(usr.Id, deleteList);
Hope it helps
You might want to check out this blog post. The ASP.NET team has a sample that includes adding and removing roles from a user.
ASP.NET Identity 2.0: Customizing Users and Roles

Save userid on database when create new object

I have a Controller where on the Create action I need the user ID.
Here's the controller.
public ActionResult Create(MyCreateViewModel model)
{
if (ModelState.IsValid)
{
var myobject = new MyObject
{
Attrib1 = DateTime.Now.Date,
Attrib2 = model.Etichetta,
UserId = // I need the user ID...
};
// Save the object on database...
return RedirectToAction("Index");
}
return View(model);
}
I'm using the UserProfile table provided with the SimpleMembership of MVC 4.
Which is the best practice in MVC 4 to manage the userID across the application?
Do I have to include a User attribute inside every Entity class?
Should I use a Session[] variable or what?
You can use this line to get the userId from the UserProfiles table.
var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
You can also use this function to get the users complete profile, including any custom columns you may be populating.
public static UserProfile GetUserProfile()
{
using (var db = new UsersContext())
{
var userId = WebSecurity.GetUserId
(HttpContext.Current.User.Identity.Name);
var user = db.UserProfiles
.FirstOrDefault(u => u.UserId == userId);
if (user == null)
{
//couldn't find the profile for some reason
return null;
}
return user;
}
}

Displaying Data from the database taking Order Id as input in mvc4

I am new to asp and I would like to ask you for some help. I built store with MvcMusicStore tutorial help.Now I want to search in the database by using OrderId.As soon as the orderid is and if we click on the submit button it should display the corresponding rows from the database. My method is as follows
public ActionResult SearchOrder(int? myid)
{
var s = from sp in db.Railways
select sp;
string oid = myid.ToString();
if (!string.IsNullOrEmpty(oid))
{
s = s.Where(st => st.OrderID == (Convert.ToInt16(oid)));
}
return View(s.ToList());
}
Also i tired with the code as
public ActionResult SearchOrder(int? myid)
{
if (id != null)
{
if (ViewBag.OrderID == id.Value)
{
s = s.Where(st => st.OrderID == id);
}
}
return View(s);
}
In the second method when i tried it is neither displaying the contents nor showing the error.
Pls do help me.
Try this:
public ActionResult SearchOrder(int? myid)
{
var s = from sp in db.Railways
select sp;
if (myid.HasValue)
{
s = s.Where(st => st.OrderID == myid.Value);
}
return View(s.ToArray());
}
First your example will not work because string oid = myid.ToString(); will not be null or empty string if myid is null; Second example will fail (ViewBag.OrderID == id.Value) condition and moreover will not compile.

Update of a row in asp.net MVC 3

I've got an Edit action like this:
[HttpPost]
public ActionResult Edit(UserModel user1)
{
if (ModelState.IsValid)
{
UserManager um = new UserManager();
String mail = User.Identity.Name;
long id = um.getUserIDByemail(mail);
user user = db.users.Single(u => u.user_id == id);
user.name = user1.name;
user.cellno = user1.cellno;
db.users.Attach(user);
db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user1);
}
I've got user object exactly what I want to update. Two properties (name, cellno) of user comes from a view. When I run it I get an error:
The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.
I think you can just remove the Attach and it should work.

Resources