Magjistari Zi
Magjistari Zi

Reputation: 1

problems with html helper method

I can't figure out how to send a parameter from a dropdownlist to my model. Could someone please show me an example of how to do this?

Upvotes: 0

Views: 126

Answers (2)

atbebtg
atbebtg

Reputation: 4083

public ActionResult Edit(int id)
        {
            Affiliate affiliate = affiliateRepository.GetAffiliate(id);
            List<SelectListItem> StateList = new List<SelectListItem>();
            SelectListItem item;

            Dictionary<string, string> dictState = S127Global.Misc.getStates();


            foreach (KeyValuePair<string, string> k in dictState)
            {
                item = new SelectListItem();
                item.Text = k.Value;
                item.Value = k.Key;
                StateList.Add(item);
            }
            item = new SelectListItem();
            item.Text = " - Select State - ";
            item.Value = "";
            StateList.Insert(0, item);


            //create new select list with affiliate.state as the selected value in ViewData
            ViewData["State"] = new SelectList(StateList.AsEnumerable(), "Value", "Text",affiliate.State);
            return View(affiliate);
        }

code for view

<div class="editor-label">
    <%: Html.LabelFor(model => model.State) %>
</div>
<div class="editor-field">
    <%: Html.DropDownList("State")%>
    <%: Html.ValidationMessageFor(model => model.State) %>
</div>

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

As always you start by defining a model:

public class MyViewModel
{
    public string SelectedValue { get; set; }

    public SelectList Items 
    {
        get
        {
            return new SelectList(new[]
            {
                new SelectListItem { Value = "1", Text = "item 1" },
                new SelectListItem { Value = "2", Text = "item 2" },
                new SelectListItem { Value = "3", Text = "item 3" },
            }, "Value", "Text");
        }
    }
}

Controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // You will get the selected value inside model.SelectedValue here
        // => do something with it
        ....
    }
}

Strongly typed view:

<% using (Html.BeginForm()) { %>
    <%= Html.DropDownListFor(x => x.SelectedValue, Model.Items) %> 
    <input type="submit" value="OK" />
<% } %>

Upvotes: 2

Related Questions