Question: DropDownListFor method instead of property

Question

DropDownListFor method instead of property

Answers 2
Added at 2016-12-29 22:12
Tags
Question

Is it possible to use a method in stead of a property for an

This works:

HTML.DropDownListFor(x => x.Book, 
                     new SelectList(ViewBag.Books, 
                                    "ID", 
                                    "Title", 
                                    new { @class = "form-control"}))

that I tested does not:

HTML.DropDownListFor(x => x.Book, 
                     new SelectList(ViewBag.Books, 
                                    "ID", 
                                    "ToString()", 
                                    new { @class = "form-control"}))

Is there any way to do this?

Answers to

DropDownListFor method instead of property

nr: #1 dodano: 2016-12-29 22:12

No you cann't pass a function, If you back to SelectList MSDN documentation, you won't find any override for it take function.

SelectList MSDN

nr: #2 dodano: 2016-12-30 10:12

I found a workaround for it. For anyone who is interested in it this is what works:

book.cs

public class Book
{
    [HiddenInput(DisplayValue = false)]
    public Guid ID { get; set; }

    [Display(Name = "Booktitle")]
    public string Title { get; set; }
    [Required]
    [Display(Name = "Voornaam")]
    public string AuthorFirstName { get; set; }
    [Required]
    [Display(Name = "Tussenvoegsel")]
    public string AuthorLastName { get; set; }

    public string FullName
    {
        get { return CompleteName(); }
    }

    private string CompleteName()
    {
        return this.AuthorFirstName + " " + this.AuthorLastName; 
    }
}

View.cshtml:

@Html.DropDownListFor(x => x.Book, new SelectList(ViewBag.Books, "ID", "FullName"), new { @class = "form-control" })
Source Show
◀ Wstecz