简体   繁体   English

如何在 cshtml 视图中正确设置所选项目?

[英]How to properly set a selected item in a cshtml view?

I have this SelectList defined in my ViewModel:我在我的 ViewModel 中定义了这个SelectList

public SelectList AccomodationTypesTypes()
{
    return new SelectList(AccomodationTypes.Select(a => a.Type), "B"); 
}

AccomodationTypes.Select(a => a.Type) is an IENumerable<string> which currently consists of "A", "B", and "C". AccomodationTypes.Select(a => a.Type)是一个IENumerable<string> ,它当前由“A”、“B”和“C”组成。 According to https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.rendering.selectlist.-ctor you can provide a second parameter to indicate the selected value - hardcoded "B" in my case - but that does not work.根据https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.rendering.selectlist.-ctor您可以提供第二个参数来指示所选值 - 在我的案例 - 但这不起作用。

If it is any help, this is the snippet in the view that has the SelectList :如果有任何帮助,这是视图中具有SelectList的代码段:

<div class="form-group row">
    <label asp-for="Accomodation.AccomodationTypeId" class="col-sm-2 col-form-label">Type</label>
    <div class="col-sm-10"><select asp-for="Accomodation.AccomodationTypeId" asp-items="Model.AccomodationTypesTypes()"></select></div>
</div>

The view displays characteristics of a particular selected Accomodation.该视图显示特定选定住宿的特征。 AccomodationTypeId is a foreign key to the AccomodationType class, which denotes more general characteristics. AccomodationTypeId 是 AccomodationType 类的外键,表示更一般的特征。 In the view the user may select a different AccomodationType for the current Accomodation.在视图中,用户可以为当前的住宿选择不同的住宿类型。 When the view is rendered on screen I expect type "B" to be selected, which it currently is not.当视图在屏幕上呈现时,我希望选择类型“B”,而目前不是。 How can I accomplish this?我怎样才能做到这一点?

I worked it out by using a different overload of SelectList:我通过使用不同的 SelectList 重载来解决这个问题:

public SelectList AccomodationTypesTypes()
{
     return new SelectList(AccomodationTypes, "Id", "Type");
}

"Id" binds with the asp-for ( Accomodation.AccomodationTypeId ) in the view, and the corresponding "Type" shows in the selection list. "Id"与视图中的asp-forAccomodation.AccomodationTypeId )绑定,对应的"Type"显示在选择列表中。 Does the trick.有诀窍。

I got off in the wrong direction because return new SelectList(AccomodationTypes.Select(a => a.Type)) already gave me the dropdownlist I wanted, and according to the Microsoft article that I linked I only had to provide a second parameter to establish a selected value ("Id" probably, instead of "B" 🙂).我走错了方向,因为return new SelectList(AccomodationTypes.Select(a => a.Type))已经给了我我想要的下拉列表,根据我链接的 Microsoft 文章,我只需要提供第二个参数建立一个选定的值(可能是“Id”,而不是“B”🙂)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM