在下拉列表中获取所选项目以查看CRUD模型

问题描述 投票:1回答:2

这是通过从我的控制器添加一个视图并选择我的dto作为模板来完成的

我的DTO

public class Company_DTO
{
    public long ID_Company { get; set; }
    public string ESTATE_Company { get; set; }
}

myController的

public ActionResult UpdateCompany()
{


     ViewBag.ListOfCompanies = DependencyFactory.Resolve<ICompanyBusiness>().GetCompany(); // this return a List<int> and following what I read for viewbag this should be right.
        return View();
    }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateCompany([Bind]Company_DTO company_DTO)
        {
            try
            {
                //code    
            }
            catch
            {
                return View();
            }
        }

视图

    <div class="form-group">            
        @Html.DropDownListFor(model => model.ID_Company , ViewBag.ListOfCompanies) // Here I get an error on my @Html that my dto does nothave a list.
    </div>

我希望所选项目是ID_Company,但在这里它似乎是在我想要所选项目时尝试添加整个列表,我无法找到任何可以解决我的问题的文档或问题。

我不能编辑DTO。

感谢您的帮助,希望我足够清楚。

c# asp.net-mvc-5 html.dropdownlistfor
2个回答
1
投票

这应该可以解决您的问题:

视图

<div class="form-group"> 
    @Html.DropDownListFor(model => model.ID_Company, new SelectList(ViewBag.Accounts, "ID_Company", "ESTATE_Company"))
</div>

假设您的视图是强类型的(@model Company_DTO)。

希望这可以帮助


1
投票

考虑以下示例:

public class HomeController : Controller
{
    private List<SelectListItem> items = new List<SelectListItem>()
    {
        new SelectListItem() { Text = "Zero", Value = "0"},
        new SelectListItem() { Text = "One", Value = "1"},
        new SelectListItem() { Text = "Two", Value = "2"}
    };

    public ActionResult Index()
    {
        ViewBag.Items = items;
        return View(new Boo() { Id = 1, Name = "Boo name"});
    }


}

public class Boo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

the view:
@model WebApi.Controllers.Boo    
@Html.DropDownListFor(x=>x.Id, (IEnumerable<SelectListItem>) ViewBag.Items)

所以,ViewBag.ListOfCompanies应该包含IEnumerable。每个SelectListItem都有Text和Value属性,您需要分别分配ESTATE_Company和ID_Company。这样的事情:

var companiesList = //get companies list 
ViewBag.ListOfCompanies = companiesList.Select(x => new SelectListItem() {Text = x.ESTATE_Company, Value = x.ID_Company.ToString()});
....
@Html.DropDownListFor(x=>x.ID_Company, ViewBag.Items as IEnumerable<SelectListItem>)
© www.soinside.com 2019 - 2024. All rights reserved.