DropDownListFor方法而不是属性

时间:2016-12-29 21:06:45

标签: c# asp.net asp.net-mvc razor html.dropdownlistfor

是否可以使用方法代替

的属性

这有效:

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

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

你不能通过一个功能,如果你回到SelectList MSDN文档,你将无法找到任何覆盖它的功能。

SelectList MSDN

答案 1 :(得分:-2)

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

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" })
相关问题