mvc base controller class is null in another controller - model-view-controller

I created a basecontroller in mvc that look like this..
public abstract class BaseController : Controller
{
private readonly IDataRepository _repo = new DataRepository();
public Core.User user;
protected BaseController()
{
var user = _repo.GetUser(Membership.GetUser().ProviderUserKey.ToString());
}
}
I can see that the user gets its data but when I try to use the user class on another controller its null, what am I doing wrong here?
public class DashBoardController : BaseController
{
// GET: Overview
[Authorize]
public ActionResult Index()
{
return View(user);
}
}

You are declaring a new user variable inside the BaseController constructor;
Just remove the var keyword.
Also, you can make user variable protected.

Related

Laravel 5.1 Return a view from a class into the controller

I have the following controller:
class MyController extends Controller {
public function getTestView() {
return view("user::index");
}
}
Instead of returning the view directly from my controller method I would like to
have another object which is responsible to return this view after adding some calculation code.
This is my class:
class User extends AbstractPerson {
function __construct() {
$this->initView();
}
private function initView(){
return view('user::index');
}
}
My controller now looks like this:
class MyController extends Controller {
public function getTestView() {
return new User();
}
}
After calling this I get the following error:
UnexpectedValueException in Response.php line 395: The Response content must be a string or object implementing __toString(), "object" given.
Any ideas why? Thanks
Try following what the exception is telling:
class User extends AbstractPerson {
function __toString() {
return $this->initView();
}
private function initView(){
return view('user::index');
}
}
a controller should return a response object, you are just returning a new User object.
class MyController extends Controller {
public function getTestView() {
User u = new User();
return u->initView();
}
}

UserManager in ApiController

In my project HttpContext is a member of Controller and I can use it in AccountController : Controller. But I can't access an information about current user in ApiController in contraction like
public class AccountController : ApiController
{
public UserManager<ApplicationUser> UserManager { get; private set; }
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.Current.GetOwinContext().Authentication;
}
}
}
So how to write custom ApiController right?
In the method below user variable shows me null on breakpoint. How can I retrive current user if I know that hi is logined?
public IHttpActionResult GetUser(int id)
{
var manager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var userid = User.Identity.GetUserId();
var user = manager.FindById(userid);
var data = new Person {Name = user.UserName, Age = 99};
return Ok(data);
}
From within any controller method you can do this.GetRequestContext().User to get the currently authenticated user. The static HttpContext.Current is not supported by WebApi.
manager.FindById(userid) retrieves a user from the database as opposed to the current . To get the current user, simply access the User property within your ApiController:
public class MyApiController : ApiController
{
IPrincipal GetCurrentUser(){
return User;
}
}
This may help you:
protected string UserId { get { return User.Identity.GetUserId(); } }

Using LINQ-to-SQL containers

I'm using MVC3 and currently i'm following a practice such that I declare one instance of DB Container for every controller. I use that container instance for every request coming to that controller. If I need to go to my models for a query or sth, I send that instance as a parameter to the model's function. So for the whole application, I create and use 4-5 different instances of DB Container class. My question is, does this have a good or bad effect on my database operations? Does it matter to create a seperate container instance? What is the proper way to use container classes?
I believe the mentioned class was called DBContext before.
I am not sure it is what you mean but I can give you an example of an approach I'm following rather often:
Create a sort of 'domainservice class' for the DBContext
public class MyDomainService : IDisposable
{
private MyDbEntities dbo;
private bool isDisposed;
public MyDomainService()
{
dbo = new MyDbEntities();
}
public User GetUser(string userName)
{
return (from usr in dbo.Users
where usr.UserName == userName
select usr).SingleOrDefault();
}
public void Dispose()
{
if (isDisposed)
return;
isDisposed = true;
dbo.Dispose();
}
}
Create a custom Controller class that extends Controller or AsyncController
and override the Initialize and Dispose methods:
public class MyController : Controller
{
protected MyDomainService DomainService { get; private set; }
protected override void Initialize(System.Web.Routing.RequestContext
requestContext)
{
base.Initialize(requestContext);
DomainService = new MyDomainService();
}
protected override void Dispose(bool disposing)
{
DomainService.Dispose();
base.Dispose(disposing);
}
}
Now you can use the following approach in per example the HomeController inheriting MyController
public class HomeController : MyController
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string username)
{
var user = DomainService.GetUser(username);
if (user != null)
return RedirectToAction("Account", "Information");
return View();
}
}
This will keep your controllers rather clean.

spring controller does not work when I extend it

i try make a generic controller with some methods, so i don´t need re-writer common codes, but don´t work, why???
#Controller("/home/teste")
public class CtrlTeste extends ControladorGenericoSpring<Assistenciado>
{
public String path;
public CtrlTeste()
{
super(Assistenciado.class);
path = "/home/teste";
setPacoteServico("servico.assistenciado");
setPrefixo("Serv");
setNomeEntidade("Assistênciado");
}
#RequestMapping
public String teste(#RequestParam(value = "id", required= true)Long id, Model model)
{
Assistenciado ass = getServico().buscarPorId(id);
model.addAttribute("assistenciado", ass);
return "/home";
}
}
You're currently specifying the name of the bean. Try with:
#Controller
#RequestMapping("/home/teste")
public class CtrlTeste extends ControladorGenericoSpring<Assistenciado> {
...
}

Passing multiple models to a view using MVC3 and Ninject

I'm new to MVC3 (which is why I bought a book on it, which is why I now have this question!), so apologies if there is an obvious answer to this!
I'm following a simple example of building a shopping cart in MVC3. The book advocates the use of Ninject for dependency injection, which I'm also new to. It all seems straight forward enough with one model, in this case Product, but building upon this I am struggling to add a second model and display this in the same view where the Product model is displayed. I've tried using a View Model but all examples I find wrap several classes into one model and I can't quite figure out how to implement this in my code.
The class:
public class Product
{
public int ProductId {get;set;}
public string Name {get;set;}
}
Abstract Repository:
public interface IProductRepository
{
IQueryable<Product> Products {get;}
}
Class to associate model with database:
public class EFDbContext : DbContext
{
public DbSet<Product> Products {get;set;}
}
Product Repository which implements abstract interface:
public class EFProductRepository : IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get {return context.Products;}
}
}
Ninject binds IProductRepository to EFProductRepository in a ControllerFactory class.
Controller:
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Products);
}
}
My problem is passing repository.Products to the strongly typed view; if I need to pass another entity, which is very feasible how would I achieve this???
You can build a ViewModel which looks like the following:
public class YourViewModel
{
public List<Product> Products { get; set; }
public List<OtherEntity> OtherEntities { get; set; }
}
Then you can wrap the repository in a service which contains all the methods
you need to fulfill your requests and/or businesslogic:
public class YourService
{
private IProductRepository repository;
public List<Product> GetAllProducts( )
{
return this.repository.Products.ToList( );
}
public List<OtherEntity> GetAllOtherEntites( )
{
return this.repository.OtherEntites.ToList( );
}
}
and finally in the Controller you fill the ViewModel appropriately
public class ProductController : Controller
{
private YourControllerService service = new YourControllerService( );
// you can make also an IService interface like you did with
// the repository
public ProductController(YourControllerService yourService)
{
service = yourService;
}
public ViewResult List()
{
var viewModel = new YourViewModel( );
viewModel.Products = service.GetAllProducts( );
viewModel.OtherEntities = service.GetAllOtherEntities( );
return View( viewModel );
}
}
Now you have multiple entities on you ViewModel.
Maybe it is not directly answer to your question but it is connected.
If you correctly pass the model to view, you can handle it like this
#model SolutionName.WebUI.Models.YourViewModel
#Model.Product[index].ProductId
#Model.OtherEntity[index].OtherId
I know that it's old post but it maybe help others :)

Resources