Duk
Duk

Reputation: 927

selected value in dropdown from the database

I want to show the stored values in dropdown as a selected value. I dont know how to do this in MVC.

My code is

<%: Html.DropDownList("basic-qualification-container" + i.ToString(), 
         new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"], "Id", "Name", (IEnumerable<int>)ViewData["BasicQualificationDegrees"]), 
         new { @class = "qualification" })%> 

I select some option from dropdown and submit. After I load the page the last stored value will display. This is my problem.

Upvotes: 1

Views: 543

Answers (2)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You are probably sending the wrong value for the selectedValue parameter. You should set the value in SelectList constructor.

<%: Html.DropDownList("basic-qualification-container" + i.ToString(), 
         new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"],
                        "Id", 
                        "Name",
                        ViewData["selectedValue"]), //set selected value here
         new { @class = "qualification" })%> 

A better way to do is to put all the data in ViewData to a model and strongly type it to your view.

Here's how you would define your model:

public class SampleModel
{
    private string SelectedOption { get; set; }
    private IEnumerable<SelectListItem> Options { get; set; }
}

Then provide the values in your action method:

public ActionResult Index()
{
    //get data from db
    SampleModel model = new SampleModel
                            {
                                SelectedOption = selectedOption,
                                Options = new SelectList(options, "Id", "Name")
                            };
    return View(model);
}

After strongly typing you view to SampleModel you can use the Html.DropDownListFor helper in your view.

<%: Html.DropDownListFor(model => model.SelectedOption,
                         Model.Options,
                         new { @class = "qualification" }) %>

Upvotes: 1

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

DropDownList Helper in SomeAction View

Html.DropDownList(
    string name,
    IEnumerable<SelectListItem> selectList,
    ViewData["lastSelected"],  // String Selected Option
    object htmlAttributes) 

You can show selected value with viewData like below.

Controller

// Set Default selected
public ActionResult SomeAction()
{
    ViewData["lastSelected"] = "Default Text";
    return View();
}

And after post, you should set again viewData that is shown in selected value.

// Set selected value after posting
[HttpPost]
public ActionResult SomeAction()
{
    .....
    ViewData["lastSelected"] = "Changed Text (selected value)";
    return View();
}

Upvotes: 0

Related Questions