MVC Drop Down list with entity framework

前端 未结 4 1250
闹比i
闹比i 2020-12-20 18:42

I\'ve created an MVC project using entity framework code first. My model is simply a form that gathers information.

public class Application
{
    public          


        
4条回答
  •  鱼传尺愫
    2020-12-20 19:31

    I assume there is a States model that has a Id and a StateName property.

    Change to the list to ViewData["State"] to ensure easy binding on POST.

    Id is the value that will be sent in the POST data ie.. State = Id. The StateName is what will be displayed in the Select list. So for your model this is not correct as State is a string. So needs to be

    this.ViewData["State"] = new SelectList(db.States.ToList(), "StateName", "StateName");
    

    Then in your view

    @Html.DropDownList("State")
    

提交回复
热议问题