我可以在.cshtml中为SelectListItem指定默认值吗? [英] Can I specify the default for a SelectListItem in the .cshtml?

查看:80
本文介绍了我可以在.cshtml中为SelectListItem指定默认值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在全局.cs文件中定义了一组下拉值:

mydropdowns.cs

 公共类Foo_DropdownValues{公共静态List< SelectListItem>是{} = new List< SelectListItem>{new SelectListItem {值="false",文本=否"},new SelectListItem {Value ="true",Text ="Yes";}};... 

我在.cshtml网络表单的不同位置使用这些SelectList:

mypage.cshtml

 < div class ="form-group";id ="PC_QU10_div"< label> @ Foo_Questions.QU10</label><选择asp-for ="Foo_Answers.QU10"asp-items ="Foo_DropdownValues.NoYes"</select></div>< div class ="form-group"id ="PC_QU20_div"< label> @ Foo_Questions.QU20</label><选择asp-for ="Foo_Answers.QU20"asp-items ="Foo_DropdownValues.NoYes"</select>... 

我想指定默认的是",对于第一项,默认为否".第二呢?

问:我可以通过任何方式在.cshtml标记中指定一个显式默认值吗?在每个项目的基础上?

如果需要的话,我的应用程序是用.Net Core 3.1中的C#编写的.

解决方案

当视图指定了模型类型时,可以使用HTML Helper方法(@ Html.TextBoxFor,@ Html.CheckBoxFor,@ Html.RadioButtonFor,@ Html.DropdownListFor)等,或在输入控件中使用 asp-for 属性.

以上两种方式都确保在提交表单时将在输入控件中输入/选择的值分配给模型对象属性,并且还使用来自模型对象的相应属性值填充输入控件如果模型对象正在从服务器传递到视图.

这就是为什么在这种特殊情况下,如果下拉列表需要预先选择一个特定值(或默认选择),则需要为下拉列表分配一个值.并且可以通过在模型对象的属性中填充值来轻松实现.

请考虑以下示例:

模型类:

 公共类PersonData{公共字符串FirstName {get;放;}公共字符串LastName {get;放;}公共字符串Gender {get;放;}公共布尔IsMarried {get;放;}公共布尔IsLeftHanded {get;放;}} 

下拉列表的静态项目列表.

 公共静态类StaticValues{公共静态SelectListItem []性别{得到{返回新的SelectListItem []{new SelectListItem("Male","Male"),新的SelectListItem(女性",女性")};}}公共静态SelectListItem []是NoItems{得到{返回新的SelectListItem []{new SelectListItem("Yes","True"),新的SelectListItem(否",假")};}}} 

查看代码:

  @model PersonData;@ {ViewData ["Title"] ="Person data";}< div>< label asp-for ="FirstName">名字:</label><输入asp-for ="FirstName"/></div>< div>< label asp-for =姓氏">姓氏:</label>< input asp-for =姓氏";/></div>< div>< label asp-for =性别">名:</label><为性别"选择asp-for.asp-items ="@ StaticValues.Genders"</select></div>< div>< label asp-for ="IsMarried">已婚:</label><为"IsMarried"选择asp-for.asp-items ="@ StaticValues.YesNoItems"</select></div>< div>< label asp-for ="IsLeftHanded">左手:</label><为"IsLeftHanded"选择asp-for.asp-items ="@ StaticValues.YesNoItems"</select></div> 

在下面的Controller Action方法代码中,模型对象填充了一些属性,并为其分配了值.然后将模型对象传递给视图.

 公共异步任务< IActionResult>指数(){var personData = new PersonData();//此分配应使用John值填充文本框personData.FirstName ="John";//性别下拉列表应预先选择男性"personData.Gender =男性";//IsMarried dropwodn应该为"Yes"预选.personData.IsMarried = true;返回View(personData);} 

以下是运行应用程序时呈现的视图.

在不同的用例中,可能会存在以下要求:当模型属性没有分配值给该属性时,默认情况下需要预先选择特定值.

在这种情况下,特定的SelectListItem应将 Selected 属性设置为true.

例如,在SelectListItem的以下列表中,纽约 true 作为第三个参数传递给

我希望这可以帮助您解决问题.

I have a set of dropdown values defined in a global .cs file:

mydropdowns.cs

public class Foo_DropdownValues
{
    public static List<SelectListItem> NoYes { get; } = new List<SelectListItem>
    {
        new SelectListItem { Value = "false", Text = "No"},
        new SelectListItem { Value = "true", Text = "Yes" }
    };
    ...

I'm using these SelectLists in different places in my .cshtml web form:

mypage.cshtml

    <div class="form-group" id="PC_QU10_div">
        <label>@Foo_Questions.QU10</label>
        <select asp-for="Foo_Answers.QU10" asp-items="Foo_DropdownValues.NoYes"></select>
    </div>
    <div class="form-group" id="PC_QU20_div">
        <label>@Foo_Questions.QU20</label>
        <select asp-for="Foo_Answers.QU20" asp-items="Foo_DropdownValues.NoYes"></select>
        ...

I'd like to specify a default of "Yes" for the first item, and a default of "No" for the second?

Q: Is there any way for my to specify an explicit default in the .cshtml markup? On a per-item basis?

My app is written in C# in .Net Core 3.1, if it matters.

解决方案

When a view has a model type specified, input controls for each of the properties of model object can be created using either the HTML Helper methods (@Html.TextBoxFor, @Html.CheckBoxFor, @Html.RadioButtonFor, @Html.DropdownListFor) etc. or using asp-for attributes in the input controls.

Both of these above mentioned ways, makes sure that the value entered/selected in the input control will be assigned to the model object properties when form is submitted and also the input controls are populated with the respective property values from the model object if the model object is being passed to the view from the server.

That's why, in this particular case, if the dropdown needs to have a specific value pre-selected (or by default selected), a value needs to be assigned to the dropdownlist. And it can be easily done by populating value in the property of the model object.

Consider example below:

Model class:

public class PersonData
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Gender { get; set; }

    public bool IsMarried { get; set; }

    public bool IsLeftHanded { get; set; }
}

Static list of items for dropdownlist.

public static class StaticValues
{
    public static SelectListItem[] Genders
    {
        get
        {
            return new SelectListItem[]
            {
                new SelectListItem("Male", "Male"),
                new SelectListItem("Female", "Female")
            };
        }
    }

    public static SelectListItem[] YesNoItems
    {
        get
        {
            return new SelectListItem[]
            {
                new SelectListItem("Yes", "True"),
                new SelectListItem("No", "False")
            };
        }
    }
}

View Code:

@model PersonData;
@{
    ViewData["Title"] = "Person data";
}

<div>
    <label asp-for="FirstName">Firstname:</label>
    <input asp-for="FirstName"/>
</div>
<div>
    <label asp-for="LastName">Lastname:</label>
    <input asp-for="LastName" />
</div>

<div>
    <label asp-for="Gender">Firstname:</label>
    <select asp-for="Gender" asp-items="@StaticValues.Genders"></select>
</div>
<div>
    <label asp-for="IsMarried">Married:</label>
    <select asp-for="IsMarried" asp-items="@StaticValues.YesNoItems"></select>
</div>

<div>
    <label asp-for="IsLeftHanded">Left handed:</label>
    <select asp-for="IsLeftHanded" asp-items="@StaticValues.YesNoItems"></select>
</div>

In the following code from Controller Action method, model object is populated with a few properties with values assigned to them. And the model object is passed to the View.

public async Task<IActionResult> Index()
    {
        var personData = new PersonData();
        // This assignment should populate the text box with John value
        personData.FirstName = "John";
        // Gender dropdown should have Male pre-selected
        personData.Gender = "Male";

        // IsMarried dropwodn should have "Yes" pre-selected.
        personData.IsMarried = true;
        return View(personData);
    }

Following is the view rendered when application is run.

In a different use case, there can be a requirement where a specific value needs to be pre-selected by default when model property does not have value assigned to the property.

In such situations, specific SelectListItem should have Selected property set to true.

For example, in below list of SelectListItem New York has true passed as third argument in constructor. That will mark that item as selected be-default in the dropdownlist.

public static SelectListItem[] OfficeLocations
{
        get
        {
            return new SelectListItem[]
            {
                new SelectListItem("London", "LON"),
                new SelectListItem("New York", "NY", true),
                new SelectListItem("Singapore", "SG")
            };
        }
}

Now I will add new property OfficeLocation to PersonData class as following.

public string OfficeLocation { get; set; }

And add following code to view.

<div>
    <label asp-for="OfficeLocation">Office location:</label>
    <select asp-for="OfficeLocation" asp-items="@StaticValues.OfficeLocations"></select>
</div>

Now if the model object does not have any value assigned to OfficeLocation property, the OfficeLocation dropdown will have New York selected by default.

The view will look as following.

I hope this will help you resolve your issue.

这篇关于我可以在.cshtml中为SelectListItem指定默认值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆