1

This was easy(ish) in WebForms and no problem in WPF but I am having issues trying to populate a DropDown in MVC, then select the value from the DB..

The DB fields are returned to the controller, passed to the Modal and entered into the view like this

@code
                        Dim vProspects As CustomerService.QuestionnaireModals = CType(ViewData("QuestionnaireModals"), CustomerService.QuestionnaireModals)
                        Dim vName As String = vProspects.Prospect_Name
                        Dim vAddress As String = vProspects.Prospect_Address
                        Dim vTown As String = vProspects.Prospect_Town
                        Dim vState As String = vProspects.Prospect_State
                        Dim vZip As String = vProspects.Prospect_Zip
                        Dim vTelephone As String = vProspects.Prospect_Telephone
                        Dim vCompany As String = vName & " <br/> "
                        vCompany += vAddress & " <br/> "
                        vCompany += vTown & ", " & vState & " " & vZip & "<br/>"
                        vCompany += "Telephone: " & vTelephone
                        @Html.Raw(vCompany)

                    End Code

and the values inserted into fields - as an example a State field

@Html.TextBox("inputCompanyState", vState, New With {.id = "inputCompanyState", .class = "form-control", .style = "max-width:80px;"})

Now if I want to replace the State field with a drop down and populate with a DataTable like

Public Function ReturnStateList() As DataTable
    Try
        Dim DT As New DataTable
        With DT.Columns
            .Add("AB", GetType(String))
            .Add("Name", GetType(String))
        End With
        With DT.Rows
            .Add("0", "Select State")
            .Add("AL", "Alabama (AL)")
            .Add("AK", "Alaska (AK)")
            .Add("AZ", "Arizona (AZ)")
            .Add("AR", "Arkansas (AR)")
            .Add("CA", "California (CA)")
            .Add("CO", "Colorado (CO)")
            .Add("CT", "Connecticut (CT)")
            .Add("DE", "Delaware (DE)")
            .Add("DC", "District of Columbia (DC)")
            .Add("FL", "Florida (FL)")
            .Add("GA", "Georgia (GA)")
            .Add("HI", "Hawaii (HI)")
            .Add("ID", "Idaho (ID)")
            .Add("IL", "Illinois (IL)")
            .Add("IN", "Indiana (IN)")
            .Add("IA", "Iowa (IA)")
            .Add("KS", "Kansas (KS)")
            .Add("KY", "Kentucky (KY)")
            .Add("LA", "Louisiana (LA)")
            .Add("ME", "Maine (ME)")
            .Add("MD", "Maryland (MD)")
            .Add("MA", "Massachusetts (MA)")
            .Add("MI", "Michigan (MI)")
            .Add("MN", "Minnesota (MN)")
            .Add("MS", "Mississippi (MS)")
            .Add("MO", "Missouri (MO)")
            .Add("MT", "Montana (MT)")
            .Add("NE", "Nebraska (NE)")
            .Add("NV", "Nevada (NV)")
            .Add("NH", "New Hampshire (NH)")
            .Add("NJ", "New Jersey (NJ)")
            .Add("NM", "New Mexico (NM)")
            .Add("NY", "New York (NY)")
            .Add("NC", "North Carolina (NC)")
            .Add("ND", "North Dakota (ND)")
            .Add("OH", "Ohio (OH)")
            .Add("OK", "Oklahoma (OK)")
            .Add("OR", "Oregon (OR)")
            .Add("PA", "Pennsylvania (PA)")
            .Add("RI", "Rhode Island (RI)")
            .Add("SC", "South Carolina (SC)")
            .Add("SD", "South Dakota (SD)")
            .Add("TN", "Tennessee (TN)")
            .Add("TX", "Texas (TX)")
            .Add("UT", "Utah (UT)")
            .Add("VT", "Vermont (VT)")
            .Add("VA", "Virginia (VA)")
            .Add("WA", "Washington (WA)")
            .Add("WV", "West Virginia (WV)")
            .Add("WI", "Wisconsin (WI)")
            .Add("WY", "Wyoming (WY)")

        End With


        Return DT
    Catch ex As Exception
        ' EmailError(ex)
        Return Nothing
    End Try
End Function

and then select the value 'vState' I am lost...

Any suggestions? Thanks

Thank you Shyju for taking the time to add that code - it put me on the right track.

@Html.DropDownList("AB", vProspects.States, New With {.class = "form-control"})

cured it for me. Did spend hours trying to figure out why it wasn't working until I noticed that I had failed to return the list after filling it from the DataTable :-(

2
  • Call Html.DropDownList instead of Html.TextBox. You'll need to package your list of values appropriately, but the signature for that method will tell you what you need. Commented Jul 26, 2015 at 23:00
  • Thank you for your reply - the issue that I am having is how to get the datatable values onto the view. In WebForms I just did this as Code Behind and populated the list. Could you do a small example? The datatable is generated from a Module that contains reusable functions. Commented Jul 26, 2015 at 23:06

1 Answer 1

1

Here is the C# version of the solution. It should be simple to convert it to VB.NET

make sure your View model has properties for the dropdown. one for the dropdown options and one for the selectedItem.

for example,

public class AddUserVM
{    
    public string Name { set;get;}
    public List<SelectListItem> States { set;get;}
    public int SelectedState { set;get;}

    public AddUserVM()
    {
        Cities=new List<SelectListItem>();
    }
}

Now In your GET action method, populate the States collection of the view model and send it to the view.

public ActionResult AddUser()
{
    var addUserVM = new AddUserVM();
    addUserVM.States = GetStates();
    return View(addUserVM);
}
private List<SelectListItem> GetStates()
{
    var list = new List<SelectListItem>();
    //Hard coded for demo. You may get the items
    // from a datasource and add to the list
    list.Add(new SelectListItem { Value = "1", Text = "MI" });
    list.Add(new SelectListItem { Value = "2", Text = "OH" });
    return list;
}

Now in your view,

@model ReplaceYourNameSpaceHere.AddUserVM
@using (Html.BeginForm())
{
    <p>
        Name  @Html.TextBoxFor(s=>s.Name)
    </p>
    <p>
        State @Html.DropDownListFor(s=>s.SelectedState,Model.States,"Select")
    </p>
    <input type="submit" />
}

When user submits the form, you can read the SelectedState property to get the user's dropdown selection.

[HttpPost]
public ActionResult AddUser(AddUserVM model)
{
    if (ModelState.IsValid)            
    {
        // get the selected state
        int stateId = model.SelectedState;
        // to do : Save and redirect (PRG pattern) instead of this demo code below
        return View("Results", model);
    }
    //Reload the Cities collection again
    model.States = GetStates();
    return View(model);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reply - I am quite sure I have the controller and model working, but I am confused about s=>s.SelectedState part - what is s=>s about?
Got there in the end - thanks for posting all that code! Have marked as the answer and upvoted
@gchq: Cool ! Glad i could help.

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.