I've been using the repository pattern described in Bob Cravens blog to create my application, but I'm a bit new and still finding my way around it. I want to inject my DataService object into the constructor of my ViewModel so I can create a SelectList object, and create a drop down box in my view. However I can't seem to get the bindings to work, every time I create the ViewModel it looks for / executes the parameterless constructor! I've tried various ways using answers here on SO but to no avail. Help would be greatly appreciated.
ViewModel:
public class ServerCreateViewModel
{
public SelectList Companies { get; private set; }
public ServerCreateViewModel()
{
}
public ServerCreateViewModel(DataService _dataService)
{
Companies = new SelectList(_dataService.Companies.All(), "Id", "CompanyName");
}
Ninject module:
Bind<DataService>().ToSelf()
.InRequestScope();
var _dataService = Kernel.Get<DataService>();
Bind<ServerCreateViewModel>()
.ToSelf()
.WithConstructorArgument("_dataService", _dataService);
//Bind<ServerCreateViewModel>()
// .ToSelf()
// .WithConstructorArgument("_dataService", ctx => ctx.Kernel.Get<DataService>());
Controller:
public ActionResult Create(ServerCreateViewModel viewModel)
{
return View(viewModel);
}
The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.
Passing Data between fragments in Android using ViewModel: This is because ViewModel is tied to the activity lifecycle. To actually pass the data between fragments, we need to create a ViewModel object with an activity scope of both the fragments, initialize the ViewModel , and set the value of the LiveData object.
Defines a class used to provide values and methods to the component's view.
You shouldn't be doing that!
View Models (all models, in fact) should be just buckets with some data. They should not depend on any business logic, services, etc.
It is controller's responsibility to populate models and pass them to views.
public class ServerCreateViewModel
{
public SelectList Companies { get; private set; }
}
public ActionResult Create()
{
var viewModel = new ServerCreateViewModel
{
Companies = new SelectList(_dataService.Companies.All(), "Id", "CompanyName")
};
return View(viewModel);
}
DataService should be injected into the controller, not view model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With