I'm using asp.net mvc with angularjs for my project. How to return some extra data(smth like isOwner variable) alongside with user
object?
var isOwner = false;
if(user.Alias == User.Identity.Name)
isOwner = true;)
On the view I want to show edit button only if user requests his own page
Here's api controller:
public User GetUser(String id)
{
xRM.DAO.Model.User user = null;
using (var db = new xRMContext())
{
user = db.Users
.Include("Team").Include("Unit").Include("Location")
.FirstOrDefault(u => u.Alias.ToLower() == id.ToLower());
}
if (user == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return user;
}
and angularjs controller:
.controller('UserCtrl', ['$scope', '$location', '$routeParams', 'User', function ($scope, $location, $routeParams, User) {
$scope.user = User.get({ id: $routeParams.id })
}])
You just need to return a viewmodel instead of the User
model. The viewmodel should contain any properties that are needed by the view and not just expose all properties of the User
object. For example:
public class UserViewModel
{
public string UserName {get; set;}
public string Email {get; set;}
// more properties from User
public bool IsOwner {get; set;}
}
You obviously need to change the GetUser
action method so it returns UserViewModel
, add the logic that figures out if a user is owner and map the properties from a User
object to the viewmodel. If you find yourself mapping properties often, which can become tedious, I strongly recommend using Automapper.