ASP.Net MVC2 DropDownListFor

前端 未结 1 551
耶瑟儿~
耶瑟儿~ 2021-02-06 10:22

I am trying to learn MVC2, C# and Linq to Entities all in one project (yes, I am mad) and I am experiencing some problems with DropDownListFor and passing the SelectList to it.<

相关标签:
1条回答
  • 2021-02-06 10:36

    EDIT: So you are using Entity Framework, yes? In that case with the addition info you put in the comments, you would want to do something like this:

    public ActionResult Create()
    {
        var viewModel = new CreateViewModel(); // Strongly Typed View
    
        using(Entities dataModel = new Entities()) // 'te' I assume is your data model
        {
             viewModel.Methods = dataModel.Methods.Select(x => new SelectListItem()
             {
                  Text = x.Description,
                  Value = x.method_id.ToString()
             });
        }
    
        return View(viewModel);
    }
    

    Your strongly typed view model would be:

    public class CreateViewModel
    {
         public string SelectedMethod { get; set; }
         public IEnumerable<SelectListItem> Methods { get; set; }
    }
    

    Your view code would be:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CreateViewModel>" %>
     <%-- Note the Generic Type Argument to View Page! --%>
     <%: Html.DropDownListFor(m => m.SelectedMethod, Model.Methods) %>
    
    0 讨论(0)
提交回复
热议问题