代码之家  ›  专栏  ›  技术社区  ›  Palantir

asp.net MVC:嵌入式对象编辑

  •  0
  • Palantir  · 技术社区  · 16 年前

    我想在对象B中嵌入一个对象A的实例。我已经有一个动作和一个编辑视图,它为对象B呈现一个表单。我把它做成了一个接受B的强类型局部视图。

    我现在正在处理Create操作,所以我做b=new b();b.A=新的A();

    现在,我将为B渲染表单,然后为A调用局部视图,将其传递给B.A。

    第二种选择有可能吗?

    还是我只需要避免嵌套视图?我想,作为一种替代方案,创建一个特殊的模型对象来处理包含a和B所有值的表单,然后当这个表单验证时,我会手动填充a和B对象并保存它们。这是唯一的解决方案吗?

    3 回复  |  直到 16 年前
        1
  •  1
  •   Keith    16 年前

    你应该能够使用你所描述的A和B。

    假设我们有以下内容:

    public class B {
        public A A {get; set;}
        public string X {get; set;}
        public int Y {get;set;}
    }
    
    public class A {
        public string Z {get; set;}
    } 
    
    //then in your controller:
    
    public ActionResult Edit () {
        return View ( 
            new B {
                A = new A { Z = "AyyZee" } ,
                X = "BeeEcks",
                Y = 7
            } );
    }
    

    你的视图和嵌套的局部视图应该生成类似这样的HTML:

     <input type="text" name="A.Z" value="AyyZee" />
     <input type="text" name="X" value="BeeEcks" />
     <input type="text" name="Y" value="7" />
    

    现在,默认的模型绑定器应该能够连接起来:

    [AcceptVerbs( HttpVerbs.Post )]
    public ActionResult Edit (B input) {
        // apply changes
        //the binder should have populated input.A
    }
    

    请注意,只有当A和B都有默认构造函数并且是相对简单的类时,这才有效。如果你有更复杂的东西,你可以使用自己的活页夹:

    [AcceptVerbs( HttpVerbs.Post )]
    public ActionResult Edit ( [ModelBinder( typeof( BBinder ) )] B input) {
        //...
    }
    
    public class BBinder : IModelBinder
    {
        public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
        {
            return  
                new B {
                    A = new A { Z = Request["A.Z"] } ,
                    X = Request["X"],
                    Y = int.Parse(Request["Y"])
                };
        }
    }
    
        2
  •  1
  •   davethecoder    16 年前

    创建自己的包含A和B的自定义模型,然后从该模型创建视图 当您提交表单时,您只需更新您的自定义模型并更新/添加您的个人模型即可。

    public class CustomViewModel
    {
        public ModelA myAModel {get;set;}
        public ModelB mybModel {get;set;}
    }
    

    该模型的视图将创建一个包含a和B的表单,并使您能够 然后,您发布的表单集可用于为每个单独的模型设置值,并更新/创建然后分离。

        3
  •  0
  •   Palantir    16 年前

    我对这段代码的问题是由两件事引起的,这两件事都发生在模型类中:

    1. 字段必须是属性,而不是普通字段
    2. 缺少初始化内部对象的构造函数

    因此,上述解决方案中的类应该是:

    public class B {
      public A a {get; set;}
      public string x {get; set;}
      public int y {get;set;}
      public B() {
        a = new A();
      }
    }
    
    public class A {    
      public string z {get; set;}
      public A() {}
     }