开发者

problems with html helper method

I can't figure out how to send a parameter from a dropdownlist to my model. Coul开发者_如何转开发d someone please show me an example of how to do this?


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" />
<% } %>


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜