Dave
Dave

Reputation: 263

Retain Value on editing drop down on Razor

Want to reduce my logic on View data from drop down won't come from data base. Current code

@Html.DropDownListFor(m => m.MyViewModel.Value,
                                new List<SelectListItem> {
                                new SelectListItem { Text = "1",Value = "1" },
                                new SelectListItem { Text = "2", Value = "2" },
                                new SelectListItem { Text = "3", Value = "3" },
                                new SelectListItem { Text = "4", Value = "4" },
                                new SelectListItem { Text = "5", Value = "5" },         
                             });

Trying to achieve

 <select id="MyViewModel.name" name="MyViewModel.name">
                            <option value="">--Select--</option>
                            @for (int i = 1; i <= 5; i++)
                            {
                                <option value="@i">@i</option>
                            }
                        </select>

On submitting the form I am getting the selected value in my ViewModel i.e action but on editing am not the selected value Like

<select data-val="true" id="ddl" name="">
<option value="1">1</option>
<option value="2">2</option>
**<option selected="selected" value="3">3</option>**
<option value="4">4</option>
<option value="5">5</option>
</select>

Upvotes: 0

Views: 691

Answers (2)

user3559349
user3559349

Reputation:

You code for generating the SelectList can be simplified to

@Html.DropDownListFor(m => m.yourProperty, new SelectList(new List<int> { 1, 2, 3, 4, 5 }))

However, that code belongs in the controller, not the view, and ideally you should have a view model with property IEnumerable<SelectListItem>, for example

public class MyViewModel
{
    [Required(ErrorMessage = "...."]
    [Display(Name = "....")]
    public int? SelectedItem { get; set; } // nullable to protect against under-posting attacks
    public IEnumerable<SelectListItem> Options { get; set; }
    ....
}

and in the GET method

MyViewModel model = new MyViewModel
{
    Options = new SelectList(new List<int> { 1, 2, 3, 4, 5 })
};
return View(model);

and in the view

Html.DropDownListFor(m => m.SelectedItem, Model.Options, "Please select")

Upvotes: 1

Emil
Emil

Reputation: 281

it will be best to define the data at the control level than in Razor

so create and edit actions will return a list which will be used in DropDownListFor

but Edit will also set the selected value

Upvotes: 0

Related Questions