mvc - select a user in a list of users - asp.net

I've got a list of users and their role, and it lists all users in my SQL database. I wanna be able to select one of the users and change their role like in the pictures below. But I need help to get the "data" of the selected user.
I'm using MVC Identity if that matters.
Controller code who shows the list
var role2 = (from r in context.Roles where r.Name.Contains("Administrator") select r).FirstOrDefault();
var admins = context.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(role2.Id)).ToList();
var adminVM = admins.Select(user => new UserViewModel
{
Username = user.UserName,
RoleName = "Administrator"
}).ToList();
View code:
#foreach (var usera in Model.Administrators)
{
<td>#usera.Username</td>
<td>#usera.RoleName</td>
<td>(bootstrap modal button)</td>
bootstrap modal body:
Current Role: <strong>#usera.RoleName</strong>
Then I want to remove the "selected" user from their role and add to another.

The explanation of the question is wrong. You have mentioned "But I need help to get the "data" of the selected user". Later you again mentioned "Then I want to remove the "selected" user from their role and add to another". The thing is that you need to bind a onClick method and pass there USER ID. See my below code,
<td><button onClick="openModal(USERId)" class="btn btn-default"></button></td>
See here "openModal" is a user-defined method where I'm passing that user Id. So now when you click this, take that value and assign it in a hidden field and as you said it will open the edit modal. See my below code,
//This is my hidden field in HTML
<button Type="hidden" id="myHiddenField"/>
//Below is the script
function openModal(id)
{
$('#myHiddenField').val(id);
//And here you can open the modal
}
So now when you assign a new Role to the particular User and click on SAVE/UPDATE button, call another jQuery/ajax method like below,
$('#myUpdateBtn').click(function({
//Here you can fetch the hidden field value, that is nothing but your selected UserId
var UserId = $('#myHiddenField').val();
$.ajax(function(){
url:"pass your url here",
Type:"Put", //Pass your method type. Ex: Post, Put, etc
Data:{Id:UserId, RoleName:yourNewRoleId},
success:function(d){}
})
}))

Related

Firebase,iOS: Appending key-value pair into a child node

I have the following User Table structure in Firebase
As you can see in the user that I have opened, I have a Posts section, inside this post section holds the Id's all articles which have been posted by this user.
The issue I am facing is as follows:
When the user creates a new article it's saved within the Posts Table, after the save I return the newly generated ID which I then pass on to the user table, I trying to insert the newly created ID into the post section of the user, so I assumed the URL would be something like this:
Users/{UserId}/Posts
However all this does it create a new section called posts, it doesn't actually insert the record into the given area.
My code which isn't working is as follows:
let linkPost = [childautoID: true]
FIRDatabase.database().reference().child("Users/\(UserId)/Posts").child(UserId).setValue(linkPost)
FYI the two id's that are currently inside Posts I added manually.
I've also tried the following:
FIRDatabase.database().reference().child("Users/\(UserId)/Posts").setValue(linkPost)
However all this does it remove all existing Id's and then inserts the new id.
I prefer something like this. This automatically append the data without fetching first
FIRDatabase.database().reference().child("Users/\(UserId)/Posts").child(UserId).setValue(true)
To append a key-value pair in Firebase Database child node use this :-
Make a Firebase Database Reference to the Posts node of that currentUser FIRDatabase.database().reference().child("Users").child(FIRAuth.auth()!.currentUser!.uid).child("Posts")
Check if Posts node exists in your user's DB, If not then create one by :- parentRef.setValue([postId : "True"]) in else block.
But if Posts node does exist retrieve it as a NSMutableDictionary , set the new object to it, and then store the updated Dictionary to that node.
func storePostsToDB(postID :String!, userID : String! = FIRAuth.auth()!.currentUser!.uid){
let parentRef = FIRDatabase.database().reference().child("Users").child(userID).child("Posts")
parentRef.observeSingleEventOfType(.Value, withBlock: {(friendsList) in
if friendsList.exists(){
if let listDict = friendsList.value as? NSMutableDictionary{
listDict.setObject("True", forKey: postID)
parentRef.setValue(listDict)
}
}else{
parentRef.setValue([postID : "True"])
}
})
}
Calling the function:-
storePostsToDB("yourPostID")// If you want to store in the currentUser DB
storePostsToDB("yourPostID", userID : otherUserID)//If you want to store the post in some other users database with uid `otherUserID`

How to pass a fresh _id from a method insert into a subscription/publication?

I have an app where you can choose (or add if they don't exist!) a superhero/villain character from a certain universe on the first page; then outfit him with weapons, clothes, and gadgets on the second page (build).
I have this route defined:
Router.route('/build/:character', {
name: 'build'
waitOn: Meteor.subscribe('characters', {name: this.params.character})
//and a few other subscriptions and sessions as well for the items
//and stuff, but those don't matter here.
}
The link from the specific character, though, passes along a query as well:
<a href="{{pathFor 'build' query=this.universe}}">
So the final link could look something like this:
/build/Aquaman?DCComics
Now the page you are on will display a list of weapons and gadgets where you could also add other stuff if you so wish. Then you are supposed to drag the items you want to include onto your version of this hero.
Problem is, at this point the app doesn't know you even want to create your own hero. Maybe the user is just looking through them for fun. There's a button that the user has to click first to initialize the creating process, and that's when the actual _id is created, something like this:
Meteor.methods({
buildHero: function(heroCharacterName, heroUniverse) {
var heroToAdd = {}
heroToAdd['characterName'] = heroCharacterName
heroToAdd['universe'] = heroUniverse
heroToAdd['_createdAt'] = new Date()
CreatedHeroes.insert(heroToAdd, function() {
if (! error)
//Update the subscription somehow...
})
}
})
So, the _id that is created here in the new Collection must be passed along to a subscription somehow, because I don't want the user to see other personal heroes that have been created, only his own newly created one.
The solution I have in mind is adding the _id onto the URL in form of a hastag, and use this.params.hash in the subscription like so:
Router.route('/build/:character', {
name: 'build'
waitOn: [Meteor.subscribe('characters', {name: this.params.character}),
Meteor.subscribe('createdheroes', this.params.hash)]
}
First of all, is this a valid approach? If so, how do I accomplish it; how do I actually update the URL to include this hash?
If not, what would be a better approach?
I think you have to handle this logic in the data context or in a template helper and not in the way of subscribing/publishing.
If I was you I would besure that the newly created item is being published and subscribed by the client and modify your search query just that it only adds the newly created item.
I am not sure if I understand your question well but what I got, you will know the last _id which was used on your insert.
Instead of letting done this automatically by meteor, just use the meteor method to create / get that _id value >> see Meteor Documentation
var new_id = new Mongo.ObjectID()
col1.insert({ _id: new_id, ... });
col2.insert({ ..., ref_col1_id: new_id, ... });

Knockout conditional styling of the option elements of an "unbound" SELECT element

The various inputs on my page are bound via knockout to a view model, let's say a customer record. That's all working fine.
Now, I want to put a SELECT at the top of the page that contains a list of all customers. The user will pick a customer, the record will be fetched from the database, and the data will be bound to the view model.
My question concerns conditional styling of the items in that SELECT list. It will be bound to an array of customer objects. The Customer object definition has a function called hasExpired:
var Customer = function (id, name, expiryDate) {
this.id = id;
this.customerName = name;
this.expiryDate = expiryDate;
this.hasExpired = function() {
return this.expiryDate == null ? false : true;
};
};
The ViewModel, to which the inputs on the page are bound, looks like this:
function ViewModel() {
var self=this;
self.customerRegion = ko.observable(),
self.customerName = ko.observable(),
.
.
.
self.allCustomers = Customers, // Customers is an array of Customer objects
self.selectedCustomer = ko.observable()
}
This knockout binding works; the SELECT is correctly populated with the list of customers:
<select id="customerSelect"
data-bind="options: allCustomers,
optionsText: 'customerName',
value: selectedCustomer />
I want to style the individual OPTIONS, adding an "expired" class if appropriate.
The individual items in the Customers SELECT are not bound to the view model. The SELECT functions like a navigation menu. The options are bound to the customer objects in the allCustomers array.
How to tell knockout to consult the hasExpired property of the customer object bound to each OPTION, to determine whether that particular option should get the expired property?
I want the customer to remain in the Select list but to appear with strike-through formatting.
Does the SELECT require its own view model?
The options binding has a parameter (optionsAfterRender) that allows for additional processing of the options elements. See Note 2: Post-processing the generated options (via the linked documentation).
Unless I have misinterpreted the structure of your data models, all that is required is a callback
self.setOptionStyling = function(option, item) {
ko.applyBindingsToNode(option, {css: {expired: item.hasExpired()} }, item);
}
bound to the optionsAfterRender parameter:
<select id="customerSelect"
data-bind="options: allCustomers,
optionsText: 'customerName',
value: selectedCustomer,
optionsAfterRender: setOptionStyling" />
Where the expired css class is defined as:
.expired {
text-decoration: line-through;
}
Fiddle

Meteor: Appending data to a users profile

I'm creating new users with the following:
Accounts.createUser({
username: t.find('#username').value,
password: t.find('#password').value,
email: t.find('#email').value,
profile : {
name: t.find('#name').value,
division: 'none',
enrolled: 'false'
}
});
I need to be able to update the division field when a user choose from a drop down select. This is my template:
<template name="userProfile">
<p>Select your division</p>
<select id="division">
<option>Div1</option>
<option>Div2</option>
<option>Div3</option>
<option>Div4</option>
</select>
<button id="enrolled"> Not enrolled </button>
<p>a: {{currentUser.profile.name}}</p>
<p>b: {{currentUser.profile.division}}</p>
</template>
I have a click event which works, but what I can't figure out is how to append or modify fields in the profiles:
Template.userProfile.events({
'click #division': function(e, t) {
console.log('Selected division is: ', t.find('#division').value);
Meteor.user.profile.division = t.find('#division').value;
},
'click: #enrolled': function(e, t) {
console.log('User is enrolled? : ');
}
});
What I'd like to happen is when a user chooses a division the field in the currentUser's profile gets updated.
I have one more question but I'll put that in a separate thread.
Thanks.
The code shown will only update a local copy.
To make a permanent change requires a database write to the users collection.
Per the documentation for Meteor.users:
Users are by default allowed to specify their own profile field with
Accounts.createUser and modify it with Meteor.users.update. To allow
users to edit additional fields, use Meteor.users.allow.
If you can't get that working on the client, it is probably a matter of permissions which are enforced on the client and not on the server. Meteor.allow() specifies these permissions on the client, and anything is permitted on the server.
Exploiting that latter fact, another way to implement profile or user information updates is to use remote methods where Meteor.call() on the client sends information to be executed on the server in a function specified in Meteor.Methods(). The server function that you write and put in Meteor.Methods would then test the validity of the update according to any conditions that you might want to defined, and if valid, call Meteor.users.update() with the update to the profile.

How can I add a link with a UID from a User Reference from a table in Drupal Views

I have the following in Drupal 6:
A Master CCK type which contains a User reference field and other fields. There will only be one record per user here.
A View of this CCK, shown as a table, with one of the fields being the user ref from the CCK type. This field is initially shown as a user name, linking to the user profile.
A Second CCK type which can have several pieces of data about a particular user.
A View for this CCK type, displaying information as a table. It takes a user id as an argument (an integer)
I want to click on the user name in the master view, and be directed to the detail view for this user. To do this, I tried selecting 'Output this field as a link' on the user field. The thing available for me to replace are:
Fields
* [field_my_user_ref_uid_1] == Content: User (field_my_user_ref)
Arguments
* %1 == User: Uid
However, the [field_my_user_ref_uid_1] element is replaced by the user name, and %1 seems to get replaced with an empty string. How can I put the user id in here?
Well, I'm not sure what the right way to do this is, but I'm solving it the hacky way I seem to be solving all my Views problems: by throwing jquery at it.
Currently, the User Ref field already has a link with the user id, so I've added this to the footer:
<script type="text/javascript">
$(function() {
var $rows = $("table.views-table tbody tr");
$rows.children("td:nth-child(1)").each(function() {
var $anchor = $(this).children("a");
var linkElements = $anchor.attr("href").split("/");
var userId = linkElements[linkElements.length - 1];
$anchor.attr("href","/my_detail_view/" + userId);
});
});
</script>
I hate that I have to do it like this, but I sure do love jquery.

Resources