2

I have created a partial view to handle drop down list controls. In my model, I have a property for a list of Cost Centers.

        [UIHint("SelectionList")]
    public List<SelectListItem> CostCentersList {get; private set;}

I used the UIHint so that it knows I want to use my SelectionList.ascx I created:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<SelectListItem>>" %>

<%=Html.DropDownListFor(m=>m, Model) %>

And then, in my main view, I use the following code to get the control rendered:

<%=Html.EditorFor(m => m.CostCentersList)%>

This is working... It renders the control... but I had an issue making the control select the item I wanted selected when I call the view. I did this with some code:

                BudgetDto b = Services.BudgetServices.GetBudgetById(id);
            model = new BudgetViewModel
                        {
                            Amount = b.Amount,
                            BudgetId = id,
                            CostCenterId = b.CostCenterId,
                            Description = b.Name,
                            Deleted = b.Deleted
                        };

            foreach (var i in model.CostCentersList)
                if (i.Value == model.CostCenterId.ToString())
                    i.Selected = true;

I then return View(model).

The control is rendered as I'd expect. Problem is, when I click Submit, my Model.CostCenterId is 0, and Model.CostCenterList is NULL. I can't seem to get the selected value back from the control.

1 Answer 1

2

To make a dropdown list you need two properties: one that represents the selected value and is bound to it and a list of SelectListItem. In your case you have only a list. So you need an intermediary view model:

public class DropDownViewModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then on your view model have:

[UIHint("SelectionList")]
public DropDownViewModel CostCentersList { get; set; }

and your editor template:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<DropDownViewModel>" %>
<%= Html.DropDownListFor(x => x.SelectedItemId, Model.Items) %>

and finally in your main view:

<%= Html.EditorFor(m => m.CostCentersList) %>

Now you could use the SelectedItemId property to set/get the value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.