1

I am using MVC4 for the first time. I got some basics of its logic.

I want display a drop down list with some dynamic contents (data are from database) in it.

How can I use model, view and controller to implement this? Please help me with sample code..

tereško
  • 58,060
  • 25
  • 98
  • 150
myaseedk
  • 1,948
  • 1
  • 14
  • 12

2 Answers2

1

You may refer this post for details. Since you have just got a basic ideas on MVC, the post also has a basic example of adding dropdownlist in MVC using the sample NorthWind databases.

Community
  • 1
  • 1
R.C
  • 10,417
  • 2
  • 35
  • 48
1

This should be a good start for you.

Models\FooModel.cs

public class FooModel
{
    public string Key { get; set; }
    public string Text { get; set; }
}

Models\FooModelList.cs

public class FooModelList
{
    public int SelectedFooId { get; set; }
    public IEnumerable<FooModel> Foos { get; set; }
}

Controllers\HomeController.cs

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new FooListModel
                        {
                            SelectedFooId = 0,
                            Foos = GetFooModels()
                        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(FooListModel model)
    {
        if (ModelState.IsValid)
        {
            // do something with model
            return RedirectToAction("View", "Foo", new { Id = model.Key });
        }

        // somethings wrong.. 
        model.Foos = GetFooModels();
        return View(model);
    }

    private IEnumerable<FooModel> GetFooModels()
    {
        var dbContext = new FooDbContext();
        var fooModels = dbContext.Foos.Select(x =>
                            new FooModel
                            {
                                Key = x.Key,
                                Value = x.Value
                            };

        return fooModels.ToList();
    }
}

Views\Home\Index.cshtml

@model MvcApp.Models.FooListModel
@{
    var fooList = new SelectList(Model.Foos, "Key", "Value");
}

@using (Html.BeginForm("DealSummaryComparison", "Reporting", FormMethod.Post)) {
    <div>
        Foos: @Html.DropDownListFor(x => x.SelectedFooId, fooList)
    </div>
    <div>
        <input type="submit" value="Submit" />
    </div>
}
shuniar
  • 2,592
  • 6
  • 31
  • 38