我的模型看起来像这样:
public List<SelectListItem> Interests { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "Buyers Agent", Text = "Buyers Agent" },
new SelectListItem { Value = "Showing Agent", Text = "Showing Agent" },
new SelectListItem { Value = "Realtor Associate", Text = "Realtor Associate" },
new SelectListItem { Value = "Transaction Coordinator", Text = "Transaction Coordinator" },
new SelectListItem { Value = "Guest Blog Writer", Text = "Guest Blog Writer" }
};
视图如下所示:
<div>
<label for="Interests" class="control-label col-sm-2" style="padding-left: 0px;">Your Interests: </label>
<select asp-for="Interests" asp-items="Model.Interests"></select>
</div>
并呈现给:
<div>
<label for="Interests" class="control-label col-sm-2" style="padding-left: 0px;">Your Interests: </label>
<select id="Interests" multiple="multiple" name="Interests">
<option value="Buyers Agent">Buyers Agent</option>
<option value="Showing Agent">Showing Agent</option>
<option value="Realtor Associate">Realtor Associate</option>
<option value="Transaction Coordinator">Transaction Coordinator</option>
<option value="Guest Blog Writer">Guest Blog Writer</option>
</select>
</div>
如果选择了项目,则会将其回发,但控制器调用会在“兴趣”中显示0项。模型的属性。控制器如下所示:
[HttpGet]
[AllowAnonymous]
public IActionResult Interest()
{
var model = new InterestFormViewModel();
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult Interest(InterestFormViewModel model)
{
// A breakpoint and watch show model.Interests to have a count of 0.
return View("HRThanks");
}
我必须忽略一些明显的东西,有人可以告诉我它可能是什么吗?谢谢!
答案 0 :(得分:2)
<select>
元素回发单个值(或<select multiple>
的情况下的简单值数组。您不能将您的选择绑定到Interests
,因为它是一个集合复杂对象(SelectListItem
)。
您的模型需要一个属性来绑定选定的值。如果你想要一个下拉列表,那么(比如说)
public string SelectedItem { get; set; }
并在视图中
<label for="SelectedItem" ...</label>
<select asp-for="SelectedItem" asp-items="Model.Interests"></select>
或者如果你想要一个列表框,那么
public IEnumerable<string> SelectedItems { get; set; }
并在视图中
<select asp-for="SelectedItems" asp-items="Model.Interests"></select>
请注意,在将模型传递给视图之前,在GET方法中设置SelectedItem
(或SelectedItems
)的值,并且其值与其中一个选项匹配,然后该选项最初将被选中。