Patrick Fritch
Patrick Fritch

Reputation: 199

Using a function in another controller?

I made another controller to hold functions I use a lot, but when I try to use the function in another controller I get an error like this

Object reference not set to an instance of an object.

Here's my new controller

using Test.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;

namespace Test.Controllers
{
public class DefaultController : Controller
{
    private dbEntities db = new dbEntities();

    public User GetUser()
    {
        string UserId = (Session["UserId"] != null) ? Session["UserId"].ToString() : User.Identity.GetUserId();

        var Data = from a in db.User
                   where a.AspNetUserId.Equals(UserId)
                   select a;

        return Data.FirstOrDefault();
    }
}
}

Here's where I use

    [HttpPost]
    public void Edit(int Id)
    {
        var Default = new DefaultController();
        var User = Default.GetUser();

        db.SaveChanges();
    }

Any tips on how to use the same function in another controller or many controllers, since it's a piece of code I use a lot?

Upvotes: 0

Views: 459

Answers (2)

IndieTech Solutions
IndieTech Solutions

Reputation: 2539

@vendettamit answer is correct , i want to propose a different solution/approach from a different prospective that will help you a lot along the way , especially if your application is getting bigger and bigger and many calls and interaction will be needed between all of your classes. First thing i would recommend is using a class that manages specifically all of the transactions related the current user, logged in user ... and also inject it for any implementation you might need in your application.

Here's an example that extend the functionality of your posted class:

Interface:

 public  interface ICurrentUser
    {
        string DisplayName { get; }
        bool IsAuthenticated { get; }
        string UserID { get; }
        //bool isCustomer { get; }
        bool IsInRole(string role);
    }

concrete class:

 class Currentuser : ICurrentUser
    {
        public Currentuser(IPrincipal principal)
        {
            if (principal == null) throw new ArgumentNullException("principal");
            IsAuthenticated = principal.Identity.IsAuthenticated;
            DisplayName = principal.Identity.GetUserName();
            UserID = principal.Identity.GetUserId();
            //IsAuthenticated = identity.IsAuthenticated;
            //DisplayName = identity.GetUserName();

            _systemPrincipal = principal;




        }

        private readonly IPrincipal _systemPrincipal;

        public string DisplayName { get; private set; }
        public bool IsAuthenticated { get; private set; }
        public string UserID { get; private set; }
       // public bool isCustomer { get; private set; }

        public bool IsInRole(string role)
        {
            return _systemPrincipal.IsInRole(role);
            //return true;
            }

        }

DI binding:(Using Ninject , but you can use any other container)

kernel.Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>();
kernel.Bind<IPrincipal>().ToMethod(c => HttpContext.Current.User);
kernel.Bind<ICurrentUser>().To<Currentuser>();

Anywhere in your other classes you can call it like this:

class Implementation
 {
     private ICurrentUser Currentuser ;
    ...
     //constructor injection
    Implementation (IcurrentUser u)
   {
     Currentuser = u;
   }

  [HttpPost]
    public void Edit(int Id)
    {

        var User = Currentuser.GetUser();

        db.SaveChanges();
    }




}

Upvotes: 1

vendettamit
vendettamit

Reputation: 14677

Create a base controller class and inherit your controller from the base class where you need to use the common function.

E.g.

public abstract class BaseController : Controller
{
    private dbEntities db = new dbEntities();

    public User GetUser()
    {
        string UserId = (Session["UserId"] != null) ? Session["UserId"].ToString() : User.Identity.GetUserId();

        var Data = from a in db.User
                   where a.AspNetUserId.Equals(UserId)
                   select a;

        return Data.FirstOrDefault();
    }
}

And then inherit the class where the common functionality is needed.

public class SomeOtherController : BaseController 
{
  [HttpPost]
    public void Edit(int Id)
    {
        var User = GetUser();
        db.SaveChanges();
    }
 }

Upvotes: 3

Related Questions