0

I have declared a SelectListItem object in my controller, I able to populate them into my DropDownList in Create() page, however I am having problem trying to get value from model to set the selected value of the DropDownList in Edit() page.

Code of Create() in controller:

public ActionResult Create()
    {
        var tagList = new List<SelectListItem>();
        tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
        tagList.Add(new SelectListItem() { Text = "Promo", Value = "Promo" });
        tagList.Add(new SelectListItem() { Text = "Limited", Value = "Limited" });
        tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
        tagList.Add(new SelectListItem() { Text = "New", Value = "New" });

        var catList = new List<SelectListItem>();
        catList.Add(new SelectListItem() { Text = "Men", Value = "Men" });
        catList.Add(new SelectListItem() { Text = "Women", Value = "Women" });
        catList.Add(new SelectListItem() { Text = "Sport", Value = "Sport" });
        catList.Add(new SelectListItem() { Text = "Casual", Value = "Casual" });

        var statusList = new List<SelectListItem>();
        statusList.Add(new SelectListItem() { Text = "Available", Value = "Available" });
        statusList.Add(new SelectListItem() { Text = "Unavailable", Value = "Unavailable" });

        ViewBag.tagDropDown = tagList;
        ViewBag.catDropDown = catList;
        ViewBag.statusDropDown = statusList;
        return View();
    }

I am able to populate the DropDownList in Create() view page using all the Viewbag(s).

However now I wished to populate the DropDownList in Edit() view page at the same time set selected value from the model.

Below are the codes from Edit() view page:

<div class="form-group">
        @Html.LabelFor(model => model.category, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.category, new SelectList(ViewBag.catDropDown, "value", "text"), htmlAttributes: new { @class = "form-control" })
        </div>
</div>

1 Answer 1

1

All you need to do is to set the category property value of your view model object in your Edit action method.

public ActionResult Edit(int id)
{
  var vm=new YourViewModel();
  vm.category="Sport";   // Replace this hard coded value with value from db
  // to do : Load ViewBag.catDropDown
  return View(vm);
}

Now the DropDownListFor helper method will make the option "Sport" selected, assuming your view is strongly typed to YourViewModel

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.