开发者

How to read the selected items in an Html.ListBox at postback time

I have a search page on my MVC site that contains a list of strings that I think the user might wish to search for in my database. This list of strings is available in my model class, so I can populate an Html.ListBox with those strings thus:

<%=Html.ListBox("SearchStrings", new SelectList(Model.SearchStrings)) %>

My problem is, how can I tell which strings the user selected in that list in my postback action?

Any help would be most appreciated.开发者_StackOverflow中文版


It is not clear what is your model type but here's an example with a simple model:

<%= Html.ListBox(
    "SearchStrings", 
    new SelectList(
        Enumerable.Range(1, 5).Select(i => new { 
            Id = i, Text = "text " + i 
        }),
        "Id", "Text"
    )
 ) %>

This indicates that the Id property will be used as a value and the Text property as the text of the list. When you submit the form you could have the following action method:

[HttpPost]
public ActionResult Index(string[] searchStrings)
{
    return View();
}

In this action the searchStrings array will be filled with the values of the selected strings.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜