DropDownListFor 方法而不是 属性

DropDownListFor method instead of property

是否可以使用一种方法代替 属性 用于

这个有效:

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

我测试的没有:

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

有什么办法吗?

不,您不能传递函数,如果您返回 SelectList MSDN 文档,您将找不到任何覆盖它的函数。

SelectList MSDN

我找到了解决方法。 对于任何对此感兴趣的人来说,这是有效的:

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" })