MVC get data from GridView to display on View - asp.net-mvc

Let me see if I can make it more clear of what im looking for.
I have a view 'UpdateLead'
on the GET in my controller I have..
[HttpGet]
public ActionResult UpdateLead()
{
LoginUser user = Session["User"] as LoginUser;
if (user != null)
{
BusinessLead bl = new BusinessLead();
bl.Name = "some stuff";
return View(bl1);
}
return RedirectToAction("Login", "Main");
}
SO when I see the View, the 'name' field has text "some stuff"..
but what i want is basically to get that 'name' information from a gridview that is on another view called 'ViewLeads'. The gridview is an Infragistics grid. So basically if the user selects the 3rd user in the grid, I want to return all the data for that user (user ID 3). Im very new to MVC and I'm totally lost right now. Thanks!

You could add a parameter of name to the action. If I understand what you're doing in your code correctly....
[HttpGet]
public ActionResult UpdateLead(String name = "")
{
if (!String.IsNullOrEmpty(name))
{
LoginUser user = name as LoginUser;
BusinessLead bl = new BusinessLead();
bl.Name = "some stuff";
return View(bl1);
}
if (user != null)
{
LoginUser user = Session["User"] as LoginUser;
BusinessLead bl = new BusinessLead();
bl.Name = "some stuff";
return View(bl1);
}
return RedirectToAction("Login", "Main");
}
To do this by Id:
[HttpGet]
public ActionResult UpdateLead(Int32 UserId = -1)
{
LoginUser user = Session["User"] as LoginUser;
if (UserId > -1)
{
BusinessLead bl = new BusinessLead();
bl.Name = "some stuff";
bl = GetUserInfoById(UserId); // Some method you need to make to populate your BusinessLead class based on the id field
return View(bl1);
}
if (user != null)
{
BusinessLead bl = new BusinessLead();
bl.Name = "some stuff";
return View(bl1);
}
return RedirectToAction("Login", "Main");
}
You could then use Html.ActionLink in your gridview
#Html.ActionLink(UserName, "UpdateLead" "ControllerName", new {name=UserName}, null)
Regarding your comment: Html.ActionLink generates the link for you. If you wanted to incorporate this manually, you could try something like this:
column.For(x => x.Name).Template("<a href='UpdateLead?name=${Name]'style='color:blue;'>${Name}</a>").HeaderText("Name").Width("10%‌​");
Edit I just noticed that you mentioned (user ID 3). You can do the same thing by passing an integer. You can either have it nullable and check the value, or default it to 0 or some other number that it could never be to check against.

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

How to redirect view in separate target window

I am using visual studio 2012 and mvc4.
I want to open CertDet view in separate window
In index view I have used submit with post method.
My Controller -
[HttpPost]
[AllowAnonymous]
public ActionResult Index(ModelCertificate cert)
{
if (ModelState.IsValid)
{
dbRTCEntities objCon = new dbRTCEntities();
Mst_Catref data = objCon.Mst_Catref.Where(x => x.Catref == cert.Catref).FirstOrDefault();
if (data != null)
{
return RedirectToAction("CertDet", new { catref = data.Catref, Excise = cert.ExciseNumber, customerNm = cert.CustomerName });
}
else
ModelState.AddModelError("", "Catref not found");
}
return View();
}
public ActionResult CertDet(string catref, string Excise, string customerNm)
{
dbRTCEntities objCon = new dbRTCEntities();
Mst_Catref data = objCon.Mst_Catref.Where(x => x.Catref == catref).FirstOrDefault();
ModelCertificate cert = new ModelCertificate();
return View(cert);
}
You should need something like this on your View:
#Html.ActionLink("CertDet", "CertDet", new { catref = data.Catref, Excise = cert.ExciseNumber, customerNm = cert.CustomerName }, new {target = "_blank"})
This will render something like this in a new window;
CertDet

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");

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