0

I am using MVC 2.

I have 5 view models and each has different message properties that i need to populate from the DB. The property names are different, per the message type.

In the view models, i have type available, for which i need to pull the messages.

If the type is Welcome, then i want to pull the 3 welcome messages.

I want to write a generic function that i will call from each action. This generic function will then look at the object being passed and its type property and then will fill the message properties specified in this view model. How can i accomplish this? From my actions, i don't want to call a separate function for each messages type.

I am trying to do some thing like following:

public void GetMessage(object viewModel, bool isCheckMessages)
        {
            viewModel = (AnnualReportWelComeViewModel)viewModel;

        }

But the viewModel in this instance is not picking properties specified in AnnualReportWelComeViewModel.

Am i thinking straight here or just making it way over complicated than it needs to be?

4

2 回答 2

1

您的代码的问题是您在转换类型时重用了相同的变量。你viewModel的 is 类型object,即使你尝试将它转换为另一种类型,你仍然会看到它为object. 您应该尝试以下方法:

public void GetMessage(object viewModel, bool isCheckMessages)
{
  var reportMessage = viewModel as AnnualReportWelComeViewModel;
  if (reportMessage != null)
  {
    // viewModel passed was of type AnnualReportWelComeViewModel
  }
}

如果您希望此功能检查许多可能的类型,viewModel那么您可以执行以下操作:

public void GetMessage(object viewModel, bool isCheckMessages)
{
  if (viewModel is AnnualReportWelComeViewModel)
  {
     var reportMessage = viewModel as AnnualReportWelComeViewModel;
     // ...
  }
  else if (viewModel is MonthlyReportWelComeViewModel)
  {
     var reportMessage = viewModel as MonthlyReportWelComeViewModel;
     // ...
  }

}
于 2013-06-06T05:24:51.687 回答
0

您应该创建接口 IViewModelWithMessage 并从中继承所有视图模型。

public interface IViewModelWithMessage
{
    string Message { get; set; }
}

在您的视图模型中,您应该将继承的属性 Message 映射到此模型消息:

public class AnnualReportWelComeViewModel : IViewModelWithMessage
{
    public string ViewModelMessage { get; set; }
    ....
    string IViewModelWithMessage.Message {
        get { return ViewModelMessage; }
        set { ViewModelMessage = value; }
    }
}

用接口的 Message 属性做你想做的事,这个值将被传递给其他属性。

public void GetMessage(IViewModelWithMessage viewModel, bool isCheckMessages)
{
    ...
    viewmodel.Message = ...
}
于 2013-06-06T05:31:49.423 回答