C# mvc 3 using selectlist with selected value in view

前端 未结 2 1180
死守一世寂寞
死守一世寂寞 2020-11-27 16:41

I\'m working on a MVC3 web application. I want a list of categories shown when editing a blo from whe applications managements system. In my viewmodel i\'ve got the followin

相关标签:
2条回答
  • 2020-11-27 17:10
    @Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId)
    

    Here you are not properly using the helper method. The first argument must be a property on your view model which will contain the currently selected value. It should be a scalar property, not a collection.

    So in your view model you need to add such property:

    [Display(Name = "Categorie")]
    public IEnumerable<SelectListItem> Categories { get; set; }
    public string SelectedValue { get; set; }
    

    And in your controller action:

    var selectList = listOfCategories.Select(x => new SelectListItem {
        Text = x.Name, 
        Value = x.Id.ToString() 
    }).ToList();
    
    var viewModel = new BlogModel
    {
        BlogId = blogToEdit.Id,
        Active = blogToEdit.Actief,
        Content = blogToEdit.Text,
        Title = blogToEdit.Titel,
        Categories = selectList,
        // this is what sets the selected value
        SelectedValue = blogToEdit.Category.Id 
    };
    

    And in your view simply:

    @Html.DropDownListFor(x => x.SelectedValue, Model.Categories)
    
    0 讨论(0)
  • 2020-11-27 17:28

    I'm pretty sure I've used the selected=true property of a select list item to good effect before. One problem I had was a conflicting value in ViewData.

    0 讨论(0)
提交回复
热议问题