如何在控制器

时间:2016-06-09 07:31:02

标签: asp.net-mvc

我正在使用ViewModel在我的asp .net MVC应用程序中创建视图。在这个视图中,我需要绑定一个下拉列表(Successfully binded)。 问题:我想在下拉列表中添加带有值的额外项目,如“select”,“0”

这是我的Viewmodel:

 public class PagesViewModel
{
    public int Id { get; set; }

    [Required]
    [Display(Name = "Page Name")]
    public string PageName { get; set; }


    [Display(Name = "Parent Page")]
    public IEnumerable<Page> Page { get; set; }
}

我的控制器:

 public ActionResult Create()
    {
        var model = new PagesViewModel
        {
            Page = db.Pages.Where(s => s.IsActive == true).OrderBy(r => r.PageName)

        };
        //--- Here I need to add extra items manually
        return View(model);
    }

我的观点:

  @Html.DropDownListFor(model => model.Id, new SelectList(Model.Page, "Id", "PageName"), "Select Parent Page", htmlAttributes: new { @class = "form-control" })

3 个答案:

答案 0 :(得分:1)

RewriteCond %{HTTP_HOST} subdomain.maindomain.com [NC]
RewriteRule ^(.*)$ http://subdomain.maindomain.com/wp-admin/$1 [L,R=301,NC]

您还可以通过linq扩展方法Insert(index,ValueToBeInserted)在顶部插入可选文本。如果你想在顶部插入,索引将为零。

如果有帮助,请标记为anser。

答案 1 :(得分:0)

试试这个

     var model = new PagesViewModel
            {
                Page = db.Pages.Where(s => s.IsActive == true).OrderBy(r => r.PageName)

            };
model.Page.Add(new Page{ Name='ABC' ... }) // You can define your properties here

答案 2 :(得分:0)

DropDownListFor助手有一个overload,允许你指定一个选项标签 - 我认为这就是你所追求的。

@Html.DropDownListFor(m => m.SomeID, Model.SomeSelectList, "Select one...", new { @class="your-class-here" })

这将呈现<option>元素,其中包含value=""属性:

<select id="SomeId" name="SomeId" class="your-class-here">
    <option value="">Select one...</option>
    <!-- ... the rest of the items from the SelectList -->
</select>

否则,您的Pages属性需要是从ICollection(如List)派生的东西,allow you to add items

型号:

public class PagesViewModel
{
    public int Id { get; set; }

    [Required]
    [Display(Name = "Page Name")]
    public string PageName { get; set; }


    [Display(Name = "Parent Page")]
    public ICollection<Page> Page { get; set; }
}

控制器:

public ActionResult Create()
{
    var model = new PagesViewModel
    {
        Page = db.Pages.Where(s => s.IsActive == true)
            .OrderBy(r => r.PageName)
            .ToList()
    };

    model.Pages.Add(new Page{ /* ... object initializers here */ });

    return View(model);
}