使用数据库创建DropDownListFor

时间:2017-06-23 17:59:50

标签: c# asp.net-mvc

我想在带有数据库的ASP.NET MVC中创建DropDownListFor,我遇到了问题"编译器错误消息:CS1955:非可调用成员' TreeViewModel.TreeItems'不能像方法一样使用。"

视图模型:

public class TreeViewModel
    {
        public List<DTree> leafs { get; set; }
        [Display(Name = "Wybierz gałąź")]
        public int SelectedRootId { get; set; }
        public IEnumerable<SelectListItem> TreeItems
        {
            get { return new SelectList(leafs, "Id", "Name"); }
        }
    }

查看:

@model Apka.ViewModels.TreeViewModel
@using (Html.BeginForm("Exercise", "Home", FormMethod.Post))
{
    @Html.DropDownListFor(m => m.SelectedRootId, Model.TreeItems());

    <input type="submit" value="przycisk"/>
}

控制器:

public ActionResult Exercise()
        {
            var dt = new DbAccess();
            var listTree = dt.GetAllTree();
            var list = new List<DTree>();

            foreach (var row in listTree)
            {
                list.Add(
                    new DTree
                    {
                        Id = row.Id,
                        Name = row.Name,
                        ParentId = (Convert.ToInt32(row.ParentId) != 0) ? Convert.ToInt32(row.ParentId) : (int?)null
                    });
            }

            TreeViewModel tvm = new TreeViewModel();
            tvm.leafs = list;
            return View();
        }

        [HttpPost]
        public ActionResult Exercise(TreeViewModel tree)
        {
            var id = tree.SelectedRootId;
            ViewBag.ID = id;
            return View();
        }

3 个答案:

答案 0 :(得分:1)

TreeItems是TreeViewModel的成员,而不是方法,所以你不能像方法那样用括号来调用它。

在您看来,请尝试更改行

@Html.DropDownListFor(m => m.SelectedRootId, Model.TreeItems());

@Html.DropDownListFor(m => m.SelectedRootId, Model.TreeItems);

答案 1 :(得分:0)

只需传递模型tvm

return View(tvm)

here demo

答案 2 :(得分:0)

您好,我们需要在上面的代码中纠正两件事:

  1. 更改此行@Html.DropDownListFor(m => m.SelectedRootId, Model.TreeItems());,如@Html.DropDownListFor(m => m.SelectedRootId, Model.TreeItems);
  2. 提示:从TreeItems中删除了括号,因为它不是方法

    2.将视图模型传递给练习视图

    更正后的代码:

    public ActionResult Exercise()
            {
                var dt = new DbAccess();
                var listTree = dt.GetAllTree();
                var list = new List<DTree>();
    
                foreach (var row in listTree)
                {
                    list.Add(
                        new DTree
                        {
                            Id = row.Id,
                            Name = row.Name,
                            ParentId = (Convert.ToInt32(row.ParentId) != 0) ? Convert.ToInt32(row.ParentId) : (int?)null
                        });
                }
    
                TreeViewModel tvm = new TreeViewModel();
                tvm.leafs = list;
    
                //passed the model 
                return View(tvm );
            }
    

    希望它有用

    由于

    KARTHIK