Home > Software engineering >  .NET dropdown list set name from object methode
.NET dropdown list set name from object methode

Time:02-28

I would like to set the text of a dynamicaly filled dropdown from a methode of the object. I tried this but didn't work.

This is my view:

<div >
    @Html.LabelFor(model => model.person, htmlAttributes: new { @class = "col-md-4 col-sm-5 col-form-label text-sm-left text-md-right" })
    <div >
        @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>

This is the Model:

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;
    }
}

CodePudding user response:

You can try to add a property to Person like this:

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;
            }
        }



    }

view:

<div >
    @Html.LabelFor(model => model.person, htmlAttributes: new { @class = "col-md-4 col-sm-5 col-form-label text-sm-left text-md-right" })
    <div >
        @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>
  • Related