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..

2 Answers 2

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>
}
Sign up to request clarification or add additional context in comments.

Comments

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.

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.