asp.net-mvc 如何在 SelectList 文本描述中组合两个字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2758734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I combine two fields in a SelectList text description?
提问by Luca Romagnoli
I want put in a selected list labels the name and surname of people of an EF model. I've tried with this:
我想在一个选定的列表中放置一个 EF 模型的人名和姓氏标签。我试过这个:
public ActionResult Insert()
{
ViewData["accountlist"] = new SelectList(time.Anagrafica_Dipendente.ToList(), "ID_Dipendente", "Surname Name", null);
Giustificativi g = new Giustificativi();
return View(g);
}
but VS returns an error, because there isn't a attribute called "surname name". how can i concat the name and surname in the selectlist label?
但是 VS 返回错误,因为没有名为“姓氏”的属性。如何在选择列表标签中连接名字和姓氏?
thanks
谢谢
回答by coderguy123
you could do something like this:
你可以做这样的事情:
ViewData["accountlist"] =
new SelectList((from s in time.Anagrafica_Dipendente.ToList() select new {
ID_Dipendente=s.ID_Dipendente,
FullName = s.Surname + " " + s.Name}),
"ID_Dipendente",
"FullName",
null);
回答by Darin Dimitrov
Add a new property to time.Anagrafica_Dipendente
which will represent the concatenation of the two properties:
添加一个新属性,time.Anagrafica_Dipendente
该属性将表示两个属性的串联:
public string Fullname
{
get
{
return string.Format("{0} {1}", Surname, Name);
}
}
and then use this:
然后使用这个:
ViewData["accountlist"] = new SelectList(
time.Anagrafica_Dipendente.ToList(),
"ID_Dipendente",
"Fullname",
null
);
Update: As of C# 6.0, the property can be more concisely written as:
更新:从 C# 6.0 开始,该属性可以更简洁地写为:
public string Fullname => string.Format("{0} {1}", Surname, Name);
Learn more about expression-bodied properties here.
在此处了解有关表达式主体属性的更多信息。
回答by Danilo Venegas
I was looking for this answer and my easy way is adding a NotMapped attribute, this is my code:
我一直在寻找这个答案,我的简单方法是添加一个 NotMapped 属性,这是我的代码:
[NotMapped]
public string FullName
{
get
{
return Name + " " + LastName;
}
}
Then you can use the normal way in the controller, this is my code, Owner the the foreign key related to AspNetUsers
然后就可以在控制器中使用正常方式了,这是我的代码,Owner相关的外键 AspNetUsers
ViewBag.Owner = new SelectList(db.AspNetUsers, "Id", "FullName", product.Owner);