0

Is it possible to have a single view model with a list that is used for a dropdownlist and also get the selected value of the dropdownlist from the view model when I post a form?

If so, how can I do this?

1
  • Post your form code. You should not need the parameter depending on how you set up your form. Commented Nov 14, 2010 at 17:57

1 Answer 1

2

Sure, as always start by defining your view model:

public class MyViewModel
{
    public int? SelectedItemValue { get; set; }
    public IEnumerable<Item> Items { get; set; }
}

public class Item
{
    public int? Value { get; set; }
    public string Text { get; set; }
}

then the controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // TODO: Fill the view model with data from
            // a repository
            Items = Enumerable
                .Range(1, 5)
                .Select(i => new Item 
                { 
                    Value = i, 
                    Text = "item " + i 
                })
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // TODO: based on the value of model.SelectedItemValue 
        // you could perform some action here
        return RedirectToAction("Index");
    }
}

and finally the strongly typed view:

<% using (Html.BeginForm()) { %>
    <%= Html.DropDownListFor(
        x => x.SelectedItemValue, 
        new SelectList(Model.Items, "Value", "Text")
    ) %>
    <input type="submit" value="OK" />
<% } %>
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.