我正在寻找一种通过循环创建下拉列表的简单方法,然后将值存储在模型中。
查看型号:
public class PreferencesShoppingCartViewModel
{
public List<CartItemPreference> CartItemPreferences{get;set;}
public class CartItemPreference{
public string Selected{get;set;}
public CartItem CartItem {get;set;}
}
}
@model MVC_COMP1562.ViewModels.PreferencesShoppingCartViewModel
看法:
@model MVC_COMP1562.ViewModels.PreferencesShoppingCartViewModel
@foreach (var cartItem in Model.CartItemPreferences)
{
@Html.DropDownListFor(m => cartItem.Selected, Model.PreferenceOptions)
}
每个下拉菜单的 ID 都是相同的。
因此,我正在为 cartItemPreferences 中的每个项目创建 div btn-group,但现在如何将选定的值分配给模型中正确的 CartItemPreference?
您需要使用for 循环而不是foreach,以便每个下拉列表都有唯一的 id。
<form action="/" method="post">
<select id="CartItemPreferences_0__Selected" name="CartItemPreferences[0].Selected">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="CartItemPreferences_1__Selected" name="CartItemPreferences[1].Selected">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<input type="submit" value="Submit"/>
</form>
public class PreferencesShoppingCartViewModel
{
public List<CartItemPreference> CartItemPreferences { get; set; }
public List<SelectListItem> PreferenceOptions { get; set; }
public PreferencesShoppingCartViewModel()
{
CartItemPreferences = new List<CartItemPreference>();
PreferenceOptions = new List<SelectListItem>();
}
}
public class CartItemPreference
{
public string Selected { get; set; }
public CartItem CartItem { get; set; }
}
public class CartItem
{
public string Sample { get; set; }
}
@model DemoMvc5.Models.PreferencesShoppingCartViewModel
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm("Index", "Home"))
{
for (int i = 0, length = Model.CartItemPreferences.Count; i < length; i++)
{
@Html.DropDownListFor(m => Model.CartItemPreferences[i].Selected, Model.PreferenceOptions)
}
<input type="submit" value="Submit"/>
}
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new PreferencesShoppingCartViewModel
{
CartItemPreferences = new List<CartItemPreference>
{
new CartItemPreference { CartItem = new CartItem { Sample = "Sample 1"}},
new CartItemPreference { CartItem = new CartItem { Sample = "Sample 2"}}
},
PreferenceOptions = new List<SelectListItem>
{
new SelectListItem {Text = "Option 1", Value = "1"},
new SelectListItem {Text = "Option 2", Value = "2"},
new SelectListItem {Text = "Option 3", Value = "3"}
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(PreferencesShoppingCartViewModel model)
{
// Do something
return View(model);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句