Displaying records from database which are equal to logged on user - asp.net-mvc-3

I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to #user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
public ActionResult Index()
{
using (var db = new mydatEntities())
{
var details = from t in db.testadtas
where t.UserID == Viewbag.UsersRecord
select t;
return View();
}
}
(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
MembershipUser currentUser = Membership.GetUser (User.Identity.Name, true /* userIsOnline */);
Viewbag.UsersRecord = currentUser.ProviderUserKey;
I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?

Just use HttpContext.User.Identity.Name

Related

Joining asp_Users db tables in LINQ using asp.net MVC

I am working on an example asp.net project using MVC, but my database is a live one which I can't make changes to (technically it's the test version of this database but my point is changes to the database aren't possible).
I use the UserID from the asp_Users table to store who makes changes to various aspects of the system, and I want to start showing the user name in various front-end tables, but how do I link the tables to get this user name?
So to clarify, I'm going to want to do this for several tables throughout the system so I was hoping I could do it using LINQ.
I can get the info I want from using the join query, but how do I pass this to my View to use?
var plans = from users in db.aspnet_Users
join import in db.Plan_Imports
on users.UserId.ToString()
equals import.User_ID
select new
{
Date = import.Date,
UserName = users.UserName
};
Sample tables
asp_Users
UserID
UserName
...
table1
ID
field1
field2
...
User_ID <--- ref to asp_Users
table2
ID
field1
field2
...
User_ID <--- ref to asp_Users
I would create a ViewModel for each view.
ViewModel is just a POCO class
public class PlanViewModel
{
public string UserName { set;get;}
public DateTime ImportDate { set;get;}
}
Then Get the Data to this ViewModel/Collection of ViewModel using LINQ Projections from your query.
public ActionResutl Show()
{
var plans = (from users in db.aspnet_Users
join import in db.Plan_Imports
on users.UserId.ToString()
equals import.User_ID
select new PlanViewModel
{
ImportDate = import.Date,
UserName = users.UserName
}).ToList();
return View(plans);
}
Now Lets make our view strongly typed to a collection of our PlanViewModel
#model List<PlanViewModel>
#foreach(var plan in Model)
{
<p>#plan.UserName</p>
<p>#plan.ImportDate.ToString()</p>
}
The solution provided by Shyju worked perfectly, and it wasn't too complex to do, however I decided that I didn't think using LINQ was appropriate in this case as the code was getting out of hand for what should be a simple call.
What I did instead was use a stored procedure to get the information, and saved it to a complex object which I passed to my view.
The code is now much neater and easier to manage, as the code above became just
var plans = db.SP_SelectImports();
Read more about stored procedure mapping here: http://dotnet.dzone.com/news/mapping-stored-procedure

mvc 3 return view with other objects

I have a details page that returns a profile view that is basically used to find the page number from the database. I also have a separate query that I would like to return in the return view but cannot figure out how to. The code I have is
public ActionResult detail(int id)
{
profile profile = db.profiles.Find(id);
var currentpage = (from s in db.profiles where id == s.profileID select s.registrationID).FirstOrDefault();
var articles = (from s in db.Articles where currentpage == s.RegistrationID select s.title).FirstOrDefault();
ViewBag.articles = articles;
ViewBag.noprofiler = " This profile currently doesn't have the email profiler selected";
return View(profile);
}
i would like to also return articles i put it into a viewbag but that is not working any ideas ?
If articles is populated then you should be able to access it in the view via ViewBag.articles
Maybe you should check what is in the articles variable here in the controller function.
Also the variable name articles suggests you're looking for a list but you are using FirstOrDefault() which would return a single object (or null).

System.Data.Objects.ObjectSet`1 instead of database table

I have database CarsDB, with Table Car in it. I whant to see the car table, but getting only System.Data.Objects.ObjectSet`1 instead of database table
public CarsBDEntities db = new CarsBDEntities();
public ActionResult Index()
{
ViewBag.Carlist = db.Cars.ToString();
return View();
}
I have make a table, then created a model from it. Using entity frameworkd and ado.net.
You don't want to use ToString; if you just return db.Cars instead, that will give you an IEnumerable that you can work with.
var cars = db.Cars;
return View(cars);
You can use this to make a Webgrid that will display your data. Razor view:
#model IEnumerable<Namespace.Models.Cars>
#{
var grid = new WebGrid(Model);
}
#grid.GetHtml()
You're trying to convert an ObjectSet to a string, which is why your getting "System.Data.Objects.ObjectSet". You'll need to pull the data out of the table to view it. For instance, something like:
string firstCarMake = db.Cars.FirstOrDefault().Make.ToString();

How to update with Entity Framework in asp.net mvc3?

I Have a table in my databse that one of the columns named NumOfView shows the number of clicks on a link. That link shows some info from a row in this table. I used onclick event in anchor tag like this:
onclick=#Url.Action("NumOfClicks", "AdvertiseHelper",new { id = Model.id[i] })
In NumOfClicks function I used this code
public void NumOfClicks (int id)
{
Ad ad1 = new Ad();
var advert = (from ad in storedb.Ads where ad.AdId == id select ad.NumOfView).First();
advert += 1;
}
advert
is the amount of
NumOfView
in table that I want to increase it 1 unit. but I don't know how to continue coding for update this value in table. Can anybody help me please?
This is the basics of how it should be done. First you have to select the record itself from the database rather than the number of clicks. Increment the number of clicks on that record, then submit the changes to the DataContext.
public void IncrementClickCount(int id)
{
var advert =
(from ad in storedb.Ads
where ad.AdId == id
select ad).Single(); // Select the row in the database represented by "ad"
advert.NumOfView++; // Perform the increment on the column
// SubmitChanges is how an update is done in Linq2Sql
// This requires a .dbml file for the database object file
// storedb.SubmitChanges(); // Assumes storedb is a valid DataContext, updates
// SaveChanges is how an update is done in EntityFramework
// It is recognizable because it uses an .edmx file for its database object
storedb.SaveChanges();
}
This was similarly asked in SO question: Entity Framework - Update a row in a table

How do I save an object that contains and EntitySet?

Say I have an User (mapped to a User table) and the Edit view (in MVC) displays a multiselectlist of Modules (mapped to a Modules table) that user can access, with the Modules pre-selected based on the User's EntitySet of Modules.
I have tried saving the User then deleting all User_Modules manually and adding them back based on what's selected on submit, but the User has a null EntitySet for User.User_Modules.
I cannot find the correct way to handle this scenario anywhere online. Can anyone help?
Edit: adding my EntitySet code
private EntitySet<UserModule> _UserModules;
[Association(Storage = "_UserModules", ThisKey="UserId", OtherKey = "UserId")]
public EntitySet<UserModule> UserModules
{
get { return this._UserModules; }
set { this._UserModules.Assign(value); }
}
Try checking if the set is loaded first
Linq to SQL
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<User>(c => c.User_Modules);
context.LoadOptions = options;
//Do query and then see if your EntitySet is still null.
Linq to entities way...
if(!User.User_ModulesReference.IsLoaded){
User.User_ModulesReference.Load();
}
//Insert delete logic here...

Resources