在ASP.Net MVC

时间:2017-04-04 15:26:11

标签: c# asp.net asp.net-mvc razor asp.net-core

我有一个表单,用户可以在其中添加某些类别并为这些类别添加一些选项。 当用户输入类别及其项目的数据时,我会在< select>中动态添加它们,其中类别为< optgroup>,因此我可以将其绑定到某些ViewModel属性,它看起来像是用户输入数据: < select asp-for =“Items”>    < optgroup label =“Brands”>        < option value =“Brand1”> Brand1< / option>        < option value =“Brand2”> Brand2< / option>        < option value =“Brand3”> Brand3< / option>        < option value =“Brand4”> Brand4< / option>    < / OPTGROUP>    < optgroup label =“Something”>        < option value =“Something1”selected> Something1< / option>        选择< option value =“Something2”> Something2< / option>        选择< option value =“Something3”> Something3< / option>        选择< option value =“Something4”> Something4< / option>    < / OPTGROUP> < /选择> 然后我尝试将它绑定到ViewModel中的Items属性,但是我可以绑定它的唯一方法是使用List< string>类型的Items。 这样我丢失了每个选项所属的组。 我怎么能把它绑定成像Dictionary< string,List< string>>这样的东西呢?在哪里我可以保持我在html上做的分组? PS。:选择将是不可见的,它只是我在一些结构中获取数据的方式,我可以在表单中提交。演示文稿将在某种标签中完成。 喜欢:

1 个答案:

答案 0 :(得分:1)

I admit, I'm not sure if this answer is quite what you are asking, since I rarely use ViewModels in my app. I'll try to update my answer if I missed the mark.

You can create a SelectList out of a Model which includes the grouping. In my example, I have a "State/Province" field which is grouped by Country.

So in my Create method of my Controller, I have:

ViewData["StateList"] = new SelectList(_context.Set<State>(), "ID", "Name", "", "CountryID");

Where the paramaters are:

new SelectList(IEnumerable items,
   string dataValueField,
   string dataTextField,
   object selectedValue,
   string dataGroupField)

Then my View takes in this SelectList to automatically group elements.

<select class="form-control" style="width: 200px;" asp-for="StateID" asp-items="ViewBag.StateList">
    <option>-- Select One --</option>
</select>

Where StateID is the database field, and ViewBag.StateList is the equivalent of the ViewData["StateList"] we created in the controller.