为嵌套的viewmodel赋值

时间:2016-04-21 10:51:11

标签: c# asp.net-mvc nested viewmodel

我对MVC有点新,并且在为嵌套视图模型分配值/数据时遇到一些困难。当我运行应用程序时,嵌套视图不显示任何内容,但是当我调试控制器时,设置了值。 嵌套视图模型是否必须在主视图模型的构造函数中实例化?怎么样?

我确实让它使用模型代替og viewmodels,但我需要添加一些验证。

示例:

**RegressionTestSuite** 
@test
1)filter1
@test
2)filter2
@test
3)filter3
@test
4)filter1 and filter2
@test
5)filter1 and filter3
@test
6)filter2 and filter3

*CommonOperations class* //abstract class
void selectCategories(String variable){}
void setFilterCriteria(filter1, filter2, filter3){}
void hoverProduct(){}
void clickAndViewDetails() {}  

// there could be many more methods which are common to finding product details across the website.

FilterTypeMobile interface
{void getMobileDetails(){}
filter variable common to mobile phones
}

                class TelevisionProduct implements FilterTypeTelevision
                {@overridden
                void getTelevisionDetails(){}
                }


FilterTypeTelevision interface
{void getTelevisionDetails(){}
filter variable common to Televisions
}

                class MobileProduct implements FilterTypeMobile
                {@overridden
                void getMobileDetails(){}
                }

在控制器中:

public class MainViewModel
{ 
public NestedViewModel NestedViewModel { get; set; }
} 
public class NestedViewModel
{
public string Name {get; set;}
}

在视图中:

public ActionResult Main()
{
var mvm = new MainViewModel();
mvm.NestedViewModel = new NestedViewModel();
mvm.NestedViewModel.Name = data.Name.ToString();
return View(mvm);
}

嵌套视图:

@model WEB.Models.MainViewModel
@{Html.RenderPartial("_NestedView", Model.NestedViewModel);}

文本框没有任何内容,而控制器有。

1 个答案:

答案 0 :(得分:1)

@model WEB.Models.MainViewModel
@Html.TextBoxFor(model => model.NestedViewModel.Name)

//should be

@model WEB.Models.NestedViewModel
@Html.TextBoxFor(model => model.Name)