.NET 下拉列表从对象方法中设置名称

.NET dropdown list set name from object methode

我想通过对象的方法设置动态填充下拉列表的文本。 我试过了,但没用。

这是我的观点:

<div class="form-group col-md-6 row">
    @Html.LabelFor(model => model.person, htmlAttributes: new { @class = "col-md-4 col-sm-5 col-form-label text-sm-left text-md-right" })
    <div class="col-md-8 col-sm-7">
        @Html.DropDownListFor(model => model.person, new SelectList(ViewBag.persons, "id", p => p.getFullName()), htmlAttributes: new { @class = "form-control"})
        @Html.ValidationMessageFor(model => model.person, "", new { @class = "text-danger" })
    </div>
</div>

这是模特:

public class Person
{
    public string id { get; set; }
    public string name{ get; set; }
    public string firstName{ get; set; }
    public string streat{ get; set; }

    public string getFullName()
    {
        return name+ " " + firstName;
    }
}

您可以尝试像这样向 Person 添加 属性:

public class Person
    {
        public string id { get; set; }
        public string name { get; set; }
        public string firstName { get; set; }
        public string streat { get; set; }
        public string fullName
        {
            get
            {
                return name + " " + firstName;
            }
        }



    }

查看:

<div class="form-group col-md-6 row">
    @Html.LabelFor(model => model.person, htmlAttributes: new { @class = "col-md-4 col-sm-5 col-form-label text-sm-left text-md-right" })
    <div class="col-md-8 col-sm-7">
        @Html.DropDownListFor(model => model.person, new SelectList(ViewBag.persons, "id", "fullName"), htmlAttributes: new { @class = "form-control"})
        @Html.ValidationMessageFor(model => model.person, "", new { @class = "text-danger" })
    </div>
</div>