如何使用匿名列表为模型在ASP.NET MVC局部视图? [英] How to use anonymous list as model in an ASP.NET MVC partial view?

查看:154
本文介绍了如何使用匿名列表为模型在ASP.NET MVC局部视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的联系的对象列表,从中,我只想属性的子集。所以我用LINQ投影创建一个匿名列表和我经过了一个局部视图。但是当我使用在局部视图该列表,编译器说,它不具有这些属性。我想最简单的例子如下,但还是我没有机会在局部视图来使用的匿名对象或列表

  VAR模型= {新名字=赛义德,姓氏=Neamati};
返回PartialView(模型);

和局部视图里面,我有:

 < H1>你的名字是@ Model.FirstName @ Model.LastName< H1>

但它说,@Model没有名字和姓氏的属性。什么是错在这里?当我使用@Model,这个字符串将呈现浏览器:

  {标题=赛义德}


解决方案

不要这样做。不通过匿名对象的意见。它们的性质是内部和其他组件不可见。视图是动态编译成ASP.NET运行时独立的动态组件。所以定义视图模型和强类型的意见。像这样的:

 公共类PersonViewModel
{
    公共字符串名字{获得;组; }
    公共字符串名字{获得;组; }
}

和则:

  VAR模型=新PersonViewModel
{
    名字=赛义德,
    姓氏=Neamati
};
返回PartialView(模型);

和在您的视图:

  @model PersonViewModel
< H1>你的名字是@ Model.FirstName @ Model.LastName< H1>

I have a list of Contact objects, from which, I just want a subset of attributes. So I used LINQ projection to create an anonymous list and I passed that to a partial view. But when I use that list in partial view, compiler says that it doesn't have those attributes. I tried the simplest case as follow, but still I have no chance to use an anonymous object or list in a partial view.

var model = new { FirstName = "Saeed", LastName = "Neamati" };
return PartialView(model);

And inside partial view, I have:

<h1>Your name is @Model.FirstName @Model.LastName<h1>

But it says that @Model doesn't have FirstName and LastName properties. What's wrong here? When I use @Model, this string would render in browser:

 { Title = "Saeed" }

解决方案

Don't do this. Don't pass anonymous objects to your views. Their properties are internal and not visible in other assemblies. Views are dynamically compiled into separate dynamic assemblies by the ASP.NET runtime. So define view models and strongly type your views. Like this:

public class PersonViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and then:

var model = new PersonViewModel 
{ 
    FirstName = "Saeed", 
    LastName = "Neamati" 
};
return PartialView(model);

and in your view:

@model PersonViewModel
<h1>Your name is @Model.FirstName @Model.LastName<h1>

这篇关于如何使用匿名列表为模型在ASP.NET MVC局部视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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