问题
Basically, I am creating a portable class library, and creating a bunch of ViewModels:
public class CustomerViewModel : ViewModelBase
{
public string FirstName { ... } // INPC
public string LastName { ... } // INPC
public string FullName
{
get { return FirstName + " " + LastName; }
}
public ICommand DoFooCommand { get; private set; } // DelegateCommand
private bool CanDoFoo(object parameter) { ... }
private void DoFoo(object parameter) { ... }
}
This is great if I want for reusability for WinRT and WPF apps, but how can I take advantage of this class for an ASP.NET MVC website? It seems as if I have to just wrap everything this class does into a Controller anyways. Also, is ICommand even usable for an ASP.NET MVC app?
I really don't want to have a client-side MVVM javascript library that is just a recoded version of my view-models.
回答1:
Direct use of this in the MVC ViewModels would be at least pointless and dysfunctional. This is because unlike MVVM in WPF the instance of the ViewModel is not kept across interactions (clicks, POSTs etc.) but re-created. Therefore the whole INPC (INotifyPropertyChanged) would not work.
ICommand would need to be enabled/disabled based on other properties to which the view would be data bound but the databinding (so to speak) in MVC is one-time (at render) which would render this concept useless, also.
MVVM and MVC are not compatible, sorry. I went through the same problem a few years ago trying to reuse stuff across platforms but I couldn't. Not even with T4 (text templates) which I tried to transform the (WPF-ish) ViewModel class into a more acceptable form for MVC.
来源:https://stackoverflow.com/questions/26002298/is-it-possible-to-take-advantage-of-the-icommand-in-an-asp-net-mvc-project