如何为 Umbraco 中的下拉列表分配默认值?

How to assign default value for dropdown list in Umbraco?

我已经创建了基于内置下拉列表的自定义数据类型,但不知道如何为列表指定默认值。默认值始终为空:

The default dropdown does not support default value

There is two way of achieving what you want

  1. create your own dropdown datatype (or use a plugin someone else has made - I am not sure which one support it, but maybe have a look at nuPickers )

  2. use a web api handler to intercept the call of getting the content value - and set a default value to your 属性 if it is empty (null)

below is some un-tested code:

first create the web api handler

public class SetDropdownDefaultHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync
            (HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        var url = request?.RequestUri?.AbsolutePath.ToLower;

        // only process when a create (getempty) or editing a specific content (getbyid) 
        if (url == "/umbraco/backoffice/umbracoapi/content/getempty"
            || url == "/umbraco/backoffice/umbracoapi/content/getbyid")
        {
            var content = (ObjectContent)response.Content;
            var data = content?.Value as PagedResult<ContentItemBasic<ContentPropertyBasic, IContent>>;

            if (data?.Items != null)
            {
                var tempResult = data?.Items?.ToList();

                foreach (var item in tempResult)
                {
                    foreach (var prop in item?.Properties?.Where(p => p?.Editor == "Umbraco.DropDown"))
                    {
                        var propStr = prop.Value?.ToString();
                        if (!propStr.IsNullOrWhiteSpace())
                        {
                            // set your default value if it is empty
                            prop.Value = "your default option prevalue id";
                        }
                    }
                }

                data.Items = tempResult;
            }
        }

        return response;
    }
}

then register it at started event

public class UmbracoEvent : ApplicationEventHandler
{
  protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
  {
    GlobalConfiguration.Configuration.MessageHandlers.Add(new SetDropdownDefaultHandler());
  }
}

your problem maybe you don't know your prevalueid - you can look it up in db or you could use datatype service to get the datatype prevalues then decide which to put as default

查看:FieldType.DropDownList 在 fieldTypes 文件夹中。

替换:<option value=""></option>

与:

var settings = Model.AdditionalSettings; <option value="">@settings["DefaultValue"]</option>

然后确保在给定表单的 Umbraco Forms 后台的下拉列表中设置默认值 属性