MVC必需字段中的Dropdownlist,带有字符串Datatype Id

时间:2014-11-16 20:01:32

标签: c# asp.net-mvc data-annotations

我在cshtml中有一个下拉列表: -

<div>
    Salutation
    @Html.DropDownListFor(
        model => model.SalutationId,
        new SelectList(Model.SalutationsList, "SalutationId", "SalutationName"),
        "Please select one",
        new { style = "width: 200px;" })<br />
</div>

在我的viewModel中,我有没有任何注释的属性为必需:

public string SalutationId { get; set; }

仍然需要下拉列表。我尝试使用以下内容: -

public string? SalutationId { get; set; }

上面给出的错误是: -

nullable error

我不知道如何处理这个问题。

请建议。

2 个答案:

答案 0 :(得分:0)

最简单的解决方案是仅使用string

public string SalutationId { get; set; }

如果它不是答案,你能描述一下,你在哪里得到错误,因为错误信息只表明上述改变。

答案 1 :(得分:0)

string是引用类型,所有引用类型的默认值均为null

删除?,添加Required数据注释,然后像这样使用它:

[Required]
public string SalutationId { get; set; }