填充 DropDownListFor 并且默认值为 guid 参数

Populate DropDownListFor and default value is guid parameter

我已经使用所有正确的值填充了 DropDownListFor。我正在传递一个 Guid 参数,但不知道如何为该 Guid 设置默认值。

查看

<div class="form-group">
  @Html.LabelFor(model => model.Parent)
  @Html.DropDownListFor(model => model.Parent, new SelectList(Model.AllParents, "Id", "Name"), string.Empty, new { @class = "form-control" })
  @Html.ValidationMessageFor(model => model.Parent)
</div>

ViewModel

public class ParentViewModel
{
     public List<Parent> AllParents { get; set; }

     [DisplayName("Parent")]
     public Guid? ParentId { get; set; }

}

控制器

[HttpGet]
public ActionResult Create(Guid? id)
{

            var parentViewModel = new ParentViewModel
            {
                AllParents = _Service.GetAll().ToList()
            };
            return View(parentViewModel);
        }
    }

您需要将 string.Empty 替换为 "Default value do you want"

@Html.DropDownListFor(model => model.Parent, new SelectList(Model.AllParents, "Id", "Name"), "Default value is here here", new { @class = "form-control" })