saucehammer
saucehammer

Reputation: 3

html.dropdownlistfor not posting back to controller in form

I have a form in an MVC application. The post back returns the model with all values populated except for the value of a drop down. This is the code I wrote for the drop down, where exactly am I going wrong?

Model:

public class ViewModel : Model 
{
    public Dictionary<int, string> ServiceFocusList { get; set; }
    public int ServiceFocus { get; set; }
}

View:

@using
(Html.BeginForm("SaveServiceRequest","ServiceRequest",FormMethod.Post))
{
    var AddLotLink = Url.Action("SaveServiceRequest", "ServiceRequest");
    var labelCol = "control-label col-md-4";
    @Html.LabelFor(model => model.ServiceFocusList, new { @class = @labelCol })
    @Html.ValidationMessageFor(model => model.ServiceFocusList)
    @Html.DropDownListFor(model => model.ServiceFocusList ,new SelectList(Model.ServiceFocusList,"Key",
     "Value", Model.ServiceFocus), "Select a Service Focus")
    <input type="submit" id="AddLotBtn" value="Add A Lot" class="saveDraft btn btn-default" urllink="@AddLotLink" />
}

Controller:

public ActionResult SaveServiceRequest(ViewModel model, long? lotId)
{
    //At this point both model.ServiceFocusList and model.ServiceFocus are null
    ServiceRequestSupport.SaveServiceRequest(model);
    RedirectToAction("CreateLotOffSR", "Lot", new {area = "Lot", model.ID});
}

Upvotes: 0

Views: 3885

Answers (2)

gunvant.k
gunvant.k

Reputation: 1086

Change your DropdownList in a view to following, you were binding it to dictionary instead of property that holds selected value.

@Html.DropDownListFor(model => model.ServiceFocus ,new SelectList(Model.ServiceFocusList,"Key",
     "Value", Model.ServiceFocus), "Select a Service Focus")

Upvotes: 0

ChrisV
ChrisV

Reputation: 1309

The first parameter of DropDownListFor is supposed to identify the property containing the selected value. You want this:

@Html.DropDownListFor(model => model.ServiceFocus, new SelectList(Model.ServiceFocusList,"Key",
 "Value", Model.ServiceFocus), "Select a Service Focus")

Upvotes: 2

Related Questions