如何在剃刀MVC asp.net两种查看模式结合 [英] How to combine two view models in razor MVC asp.net

查看:107
本文介绍了如何在剃刀MVC asp.net两种查看模式结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一些型号如下:

Lets say I have some models as follows:

public class Model1 
{
   public int ID{get;set;}
   public string Name{get;set;}
}

public class Model2 
{
    public int ID{get;set;}
    public string Name{get;set;}
}

class CommonViewModel 
{
    public string Title{get;set;}
    public Model1 model1;
    public Model2 model2;
}

和我有一个的Razor视图如下:

and I have a razor view as follows

@model ProjectName.CommonViewModel

@Html.LabelFor(m => model.Title)           
@Html.EditorFor(m => model.Title)

@Html.LabelFor(m => model.model1.Name)           
@Html.EditorFor(m => model.model1.Name)

我的控制器我有一个回这需要CommonViewModel作为参数。常见的视图模型将有标题为model1.Name值,但并非如此。为什么我怎么能得到的价值存储和后发回给控制器。

on my controller I have a post back which takes CommonViewModel as a parameter. The common view model will have a value for the Title but not for the model1.Name. Why and how can I get that value stored and sent back in the post back to the controller.

推荐答案

CommonViewModel 类有一些问题。它应该是公开的,MODEL1和MODEL2应该有getter和setter:

Your CommonViewModel class has some issues. It should be public, model1 and model2 should have getter and setter:

public class CommonViewModel
{
    public string Title { get; set; }
    public Model1 model1{get;set;}
    public Model2 model2{get;set;}
}

另外,在视图中需要解决:

Also in the view you need to fix:

@Html.LabelFor(m => m.Title)           
@Html.EditorFor(m => m.Title)

@Html.LabelFor(m => m.model1.Name)           
@Html.EditorFor(m => m.model1.Name)

在code以上的在我的测试工作正常。

The code above works fine in my test.

这篇关于如何在剃刀MVC asp.net两种查看模式结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆