0

I have the following URL: https://localhost:27635/Student/Create?PersonId=1

I also have a combobox filled with Persons which the user can use to select a Person. How can I set the combobox to have by default the PersonId from the URL?

This is the combobox code:

@Html.DropDownListFor(
    x => x.PersonId,
    new SelectList(Model.Persons, "Id", "Fullname", Model.PersonId),
    "-- Select --", new { @class = "form-control" }
)

It contains PersonIds, displaying the full name. The reason I want to use a combobox instead of saving the value from the URL directly is because I want to allow the user to change.

Another thing im curious about is if its possible to have the default -- Select -- show up if the URL id is incorrect and not in the combobox.

Thanks

1 Answers1

0

hello you can properly use something like the following post

basically there is an overload to the SelectList function you can find it in this link

so SelectList will take following

items (IEnumerable) - The items used to build each SelectListItem of the list.

dataValueField (String) - The data value field. Used to match the Value property of the corresponding SelectListItem.

dataTextField (String) - The data text field. Used to match the Text property of the corresponding SelectListItem.

dataGroupField (String) - The data group field. Used to match the Group property of the corresponding SelectListItem.

selectedValue (Object) - The selected value. Used to match the Selected property of the corresponding SelectListItem.

here is an example:

    @Html.DropDownListFor(
    m => m.CountryId, // Specifies where to store selected country Id
                      // It needs to be null for the default selection to work!

    new SelectList(Model.Countries, // IEnumerable<Country>, contains all countries loaded from a database
                   "Id",   // Use Country.Id as a data source for the values of dropdown items
                   "Name", // Use Country.Name as a data source for the text of dropdown items
                   13 // Specifies Australia (which has ID of 13) as the element selected by default
                   ),

    // Text of option that prompts user to select
    "- Please select your country -"
)