Bind a ViewModel to a DropDownListFor with a third value besides dataValueField/dataTextField

Posted by Elisa on Stack Overflow See other posts from Stack Overflow or by Elisa
Published on 2012-09-08T21:26:05Z Indexed on 2012/09/08 21:38 UTC
Read the original article Hit count: 228

Filed under:
|

When I show a list of testplanViewModels in my View and the user selects one the SelectedTestplanId is returned to the Controller post action. What should also be returned is the TemplateId which belongs to the SelectedTestplanId.

When the AutoMapper definition is run the Testplan.TestplanId is implicitly copied over to the TestplanViewModel.TestplanId. The same could be done by providing a TemplateId on the TestplanViewModel. When the user selects now a "TestplanViewModel" in the View, how can I attach the TemplateId to the controller action to access it there? The DropDownList does not allow 2 dataValueFields!

CreateMap<Testplan, TestplanViewModel>().ForMember(dest => dest.Name, opt => opt.MapFrom(src => string.Format("{0}-{1}-{2}-{3}", src.Release.Name, src.Template.Name, src.CreatedAt, src.CreatedBy)));

public ActionResult OpenTestplanViewModels()
{
    IEnumerable<Testplan> testplans = _testplanDataProvider.GetTestplans();          
    var viewModel = new OpenTestplanViewModel
    {
        DisplayList = Mapper.Map<IEnumerable<Testplan>, IEnumerable<TestplanViewModel>>(testplans)
    };
    return PartialView(viewModel);
}


public class TestplanViewModel
{      
    public int TestplanId { get; set; }     
    public string Name { get; set; }           
}


public class OpenTestplanViewModel
{
    [Required(ErrorMessage = "No item selected.")]
    public int SelectedTestplanId { get; set; } 
    public IEnumerable<TestplanViewModel> DisplayList { get; set; }       
}

OpenTestplanViewModel

@using (Html.BeginForm("Open", "Testplan"))
{ 
    @Html.ValidationSummary(false)      
    @Html.DropDownListFor(x => x.SelectedTestplanId, new SelectList(Model.DisplayList, "TestplanId", "Name"), new { @class = "listviewmodel" })  
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc