c html循环ienumerable,using Html.EditorFor with an IEnumerable | 易学教程

问题

I have a custom class:

public class Person

{

public String Name { get; set; }

public Int32 Age { get; set; }

public List FavoriteFoods { get; set; }

public Person()

{

this.FavoriteFoods = new List();

this.FavoriteFoods.Add("Jambalya");

}

}

I pass this class to my strongly typed view:

" %>

Create

Create

person.Name) %>

person.Name) %>

person.Age) %>

person.Age) %>

person.FavoriteFoods[0]) %>

person.FavoriteFoods[0]) %>

And when I browse to the page, I end up with the error message: Templates can be used only with field and property accessor expressions. After a bit of googling, I figured out that this happens because the EditorFor and LabelFor functions can only accept immediate properties of the Model object, and FavoriteFoods[0] is not an immediate property. Does anyone have a work around which would make the code work without using a string to specify the name of the control? Is that even possible? Optimally I would like to use an expression from the model to the item that needs an editor, which determines on its own the name of the control for the input.

Trying some more things, I was able to get this working using the following changes to the view:

person.Name) %>

person.Name) %>

person.Age) %>

person.Age) %>

FavoriteFoods) %>

FavoriteFoods)%>

It is important to note however that right side of the expression in EditorFor and LabelFor must be the exact name of the list you are trying to populate and the list must be of a basic type (i.e. String, Int32, etc). When I try to use complex types however, it still fails. I tried to display a list of this person class with inputs for each property and it displays all of them to the browser just fine, but then it returns a null List to my post action. How do I get the index to show up in the name of inputs for items of a list?

This was a giant help in figuring out what was going on.

回答1:

I assume this is for the FavoriteFoods list. How it has been done in ASP.NET MVC v1 was having something like this:

来源:https://stackoverflow.com/questions/1478378/using-html-editorfor-with-an-ienumerablet

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值