Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get data from static dropdown list to model in mvc4

I have one static dropdown list in my view

<select>
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
</select>

I want to bind this drop down list with my model so that when I submit selected value of drop down , I get that value from model in my controller.

Also I want to select option in drop down as per data in my model.

like image 405
vaibhav shah Avatar asked Jan 15 '23 08:01

vaibhav shah


2 Answers

I just made list item for static dropdown list & passed it to dropdown list where I binded it with my viewmodel.

 @{
   var listItems = new List<ListItem> {new ListItem {Text = "Single", Value = "Single"}, new ListItem {Text = "Married", Value = "Married"}, new ListItem {Text = "Divorse", Value = "Divorse"}};
   }
 @Html.DropDownListFor(model => model.EmployeeDetail.MaritalStatus, new SelectList(listItems),"-- Select Status --")

It works perfectly for me as it shows value which comes from model & also stores value of dropdown list in model when I submit data.

like image 52
vaibhav shah Avatar answered Jan 31 '23 01:01

vaibhav shah


Instead of constructing the drop down list in HTML, build it in your service/controller and add it to your model:

ViewModel:

public class YourViewModel
{
    public string SelectedCarManufacturer { get; set; }

    public Dictionary<string, string> CarManufaturers { get; set; }

    // your other model properties
}

Controller get action method

[HttpGet]
public ActionResult SomeAction()
{
    var model = new YourViewModel
    {
        SelectedCarManufacturer = null, // you could get this value from your repository if you need an initial value
        CarManufaturers = new Dictionary<string, string>
        {
            { "volvo", "Volvo" },
            { "saab", "Saab" },
            { "audi", "Audi" },
            /// etc.
        }
    };

    return this.View(model);
}

In your view, replace the hard coded drop down list with:

@Html.DropDownListFor(m => m.SelectedCarManufacturer , new SelectList(Model.CarManufaturers , "Key", "Value"), "Select a manufacturer...")

Controller post action method

[HttpPost]
public ActionResult SomeSaveAction(YourViewModel model)
{
    // do something with the model...
    // model.SelectedCarManufacturer 
}

OR

[HttpPost]
public ActionResult SomeSaveAction()
{
    var model = someService.BuildYourViewModel()
    this.TryUpdateModel(model);

    // do something with the model...
    someService.SaveYourViewModel(model);
}

I hope this helps...

like image 32
M.Ob Avatar answered Jan 30 '23 23:01

M.Ob