Update of a row in asp.net MVC 3 - asp.net-mvc

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.

Related

How to Pass Value from a login Page

Hello I need help please
I am creating my first asp mvc Webpage.
I created a login and registration page connected with database.
I want to pass CustomerId from the customer that logged in to a Bookings table
So that it shows bookings related to that customer only.
Bookings table has CustomerId as a foreign key. This is what I have done so far.
public class BookingController : Controller
{
// GET: Booking
public ActionResult Index(int customerId)
{
TravelExpertsEntities bookingdb = new TravelExpertsEntities();
List<Booking> bookings = bookingdb.Bookings.Where(book =>
book.CustomerId == customerId).ToList();
return View(bookings);
}
}
}
//This is from login Controller
public ActionResult Login(Customer reg)
{
if (ModelState.IsValid)
{
var details = (from userlist in db.Customers
where userlist.UserName == reg.UserName &&
userlist.Password == reg.Password
select new
{
userlist.CustomerId,
userlist.UserName
}).ToList();
if (details.FirstOrDefault() != null)
{
Session["CustomerId"] =
details.FirstOrDefault().CustomerId;
Session["Username"] = details.FirstOrDefault().UserName;
return RedirectToAction("Index", "Booking");
}
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
}
return View(reg);
}
I was able to pull all bookings but I want to filter it with the Customer that logged in.
Replace your RedirectToAction as below, to pass customerId as parameter
var CustomerIdparam=details.FirstOrDefault().CustomerId;
RedirectToAction("Index", "Booking", new{customerId=CustomerIdparam});

delete a user based on id from my databse context

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();
}

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

Conditional RedirectToAction in Controller?

I'm just wondering where, in MVC, the responsibility for determining where to redirect belongs. I think it's the controller, but I'm not sure.
In the Create action of a WorkshopItem I'm creating a new WorkshopItem from the ViewModel passed in, then saving it to the database. Part of the ViewModel is a SelectedCustomerId and CustomerName, if the SelectedCustomerId is empty and the name is empty I get the default customer entity and associate it with the item. If the Id is empty but the name is not then the user has searched for a customer but no matches were found, so I take the value and create a new customer record and attach it.
[NHibernateActionFilter]
[HttpPost]
public ActionResult Create(WorkshopItemCreateViewModel model)
{
try
{
Customer customer = null;
if (model.SelectedCustomerId == new Guid() &&
!string.IsNullOrWhiteSpace(model.CustomerName))
customer = CreateNewCustomer(model.CustomerName);
else if (model.SelectedCustomerId == new Guid() &&
string.IsNullOrWhiteSpace(model.CustomerName))
{
// Assign the System Valued customer if no customer was selected.
var id = Guid.Parse(ConfigurationManager.AppSettings["ValuedCustomerId"]);
customer = Session.QueryOver<Customer>()
.Where(c => c.Id == id)
.SingleOrDefault();
}
// other stuff
return RedirectToAction("Index");
This is working fine, but now I want to also RedirectToAction depending on whether a customer record was created or not because if a customer was created it only has a Name and I'd like to redirect to the Edit action on the Customer Controller passing the CustomerId (which I think I can do). My question is really whether this is valid to do in MVC or should this be a responsibility elsewhere?
This would look like this:
[NHibernateActionFilter]
[HttpPost]
public ActionResult Create(WorkshopItemCreateViewModel model)
{
try
{
Customer customer = null;
bool newCustomer = false;
if (model.SelectedCustomerId == new Guid() &&
!string.IsNullOrWhiteSpace(model.CustomerName))
{
customer = CreateNewCustomer(model.CustomerName);
newCustomer = true;
}
else if (model.SelectedCustomerId == new Guid() &&
string.IsNullOrWhiteSpace(model.CustomerName))
{
// Assign the System Valued customer if no customer was selected.
var id = Guid.Parse(ConfigurationManager.AppSettings["ValuedCustomerId"]);
customer = Session.QueryOver<Customer>()
.Where(c => c.Id == id)
.SingleOrDefault();
}
// other stuff
if (newCustomer)
return RedirectToAction("Edit", "Customer", new {id=customer.Id});
else
return RedirectToAction("Index");
Absolutely, the controller maintains responsibility of returning content and redirecting to the appropriate actions. You can think of the controller as almost a traffic cop, directing things where to go and sending the right stuff to the appropriate places. An example from your code above might look something like this:
if (model.SelectedCustomerId == new Guid() && !string.IsNullOrWhiteSpace(model.CustomerName))
customer = CreateNewCustomer(model.CustomerName);
return RedirectToAction("Edit", new {id = customer.Id});
else if (model.SelectedCustomerId == new Guid() && string.IsNullOrWhiteSpace(model.CustomerName)){
// Assign the System Valued customer if no customer was selected.
var id = Guid.Parse(ConfigurationManager.AppSettings["ValuedCustomerId"]);
customer = Session.QueryOver<Customer>().Where(c => c.Id == id).SingleOrDefault();
return RedirectToAction("SomeOtherMethod");
}
// other stuff
return RedirectToAction("Index");

MVC 4 Session Variable getting updated and I don't know how

I have a method to retrieve session variables, in this case Organizations. For some reason, when I call the get session method the get Organizations and pass the data to a SelectList method to handle some naming logic, the session variable is getting updated. I don't wanted the session values updated and don't understanding what is happening. Below are all the methods. What am I missing?
Controller Method:
public ActionResult Create()
{
SignUpEventFormModel model = new SignUpEventFormModel();
SelectListHelpers listHelper = new SelectListHelpers();
model.OrganizationList = listHelper.GetOrgSelectList(sessionRepository.GetUserSession().Organizations, null);
return View(model);
}
Get User Session Method:
public UserSession GetUserSession()
{
UserSession us = (UserSession)HttpContext.Current.Session["UserSession"];
if (us == null)
{
string email = HttpContext.Current.User.Identity.Name;
SessionSetupRepository sessionsetupRepository = new SessionSetupRepository(new UserRepository(null, null), new SignUpRepository(), new ActivityRepository(), new OrganizationRepository());
us = sessionsetupRepository.SetupUserSession(email);
}
return us;
}
Get Org Select List Method:
public SelectList GetOrgSelectList(IEnumerable<Organization> Orgs, int? SelectedOrgID)
{
List<Organization> OrgList = Orgs.ToList();
OrgList.Where(o => !o.IsAdmin).ToList().ForEach(o => o.Name = o.Name + " (Permission Request Required)");
if (SelectedOrgID.HasValue)
return new SelectList(OrgList, "OrganizationID", "Name", (int)SelectedOrgID);
else
return new SelectList(OrgList, "OrganizationID", "Name");
}
Created a IList parameter and converted the organizations to a list.

Resources