viewModel继承在MVC中不起作用

时间:2011-11-21 07:39:34

标签: asp.net-mvc asp.net-mvc-3

为什么我的viewModel不会被继承?我有以下viewModels:

public class BaseViewModel {

    public BaseViewModel() {
        Location = new Location { };
    }
    public Location Location { get; set; }

}

public class EditViewModel : BaseViewModel {
    public Book Book { get; set; }
}

在我的控制器中:

        var viewModel = new EditViewModel
        {
            Book = new Book { Test = "ABC" },
            Location = { City = "AAA" }
        };

当我检查viewModel的样子时,我发现它不包含位置类,即使我的视图继承自BaseViewModel。谁能明白为什么会这样。如何确保视图包含位置?

1 个答案:

答案 0 :(得分:2)

很奇怪,因为下面的编译和工作对我很好:

public ActionResult Index()
{
    var viewModel = new EditViewModel
    {
        Book = new Book { Test = "ABC" },
        Location = new Location { City = "AAA" }
    };
    return View(viewModel);
}

并在视图中:

@model EditViewModel
@Model.Location.City