getting the values from a nested complex object that is passed to a partial view

后端 未结 4 919
感动是毒
感动是毒 2020-11-22 12:32

I have a ViewModel that has a complex object as one of its members. The complex object has 4 properties (all strings). I\'m trying to create a re-usable partial view where

4条回答
  •  盖世英雄少女心
    2020-11-22 12:59

    You can try passing the ViewModel to the partial.

    @model my.path.to.namespace.MyViewModel
    @Html.TextBoxFor(m => m.ComplexModel.Name)
    

    Edit

    You can create a base model and push the complex model in there and pass the based model to the partial.

    public class MyViewModel :BaseModel
    {
        public string SomeProperty { get; set; }
    }
    
     public class MyViewModel2 :BaseModel
    {
        public string SomeProperty2 { get; set; }
    }
    
    public class BaseModel
    {
        public MyComplexModel ComplexModel { get; set; }
    }
    public class MyComplexModel
    {
        public int id { get; set; }
        public string Name { get; set; }
        ...
    }
    

    Then your partial will be like below :

    @model my.path.to.namespace.BaseModel
    @Html.TextBoxFor(m => m.ComplexModel.Name)
    

    If this is not an acceptable solution, you may have to think in terms of overriding the model binder. You can read about that here.

提交回复
热议问题