Dropdownlistfor返回null值

时间:2016-11-08 12:39:32

标签: asp.net-mvc html-helper

我有一个属性为Gender的客户类。我创建了一个包含姓名和性别类型的性别类型列表。提交表单时,我将获得空值。

查看

@Value("#{propertiesService.getProperty('helloWorld')}") 
private String helloWorld;

模型

@model MovieRentals.ViewModel.CustomerView
<div class="form-group">
    <h4>@Html.LabelFor(l => l.Customer.BirthDate)</h4>
    @Html.DropDownListFor(l => l.CustomerGender, new SelectList(Model.CustomerGender, "GenderId", "GenderType"), "Select Gender", new { @class = "form-control" })
</div>

控制器

public class CustomerView
{
    public IEnumerable<MembershipType> MembershipTypes{ get; set; }
    public Customer Customer { get; set; }
    public List<GenderClass> CustomerGender{ get; set; }
}

public class GenderClass
{
    public int GenderId { get; set; }
    public string GenderType { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您需要两个属性:一个用于保存所选值,另一个用于保存选项。保留选项的那个应该是IEnumerable<SelectListItem>。你的GenderClass课程完全是多余的。

此外,当该值的含义不明显时,使用整数id作为值是没有意义的。此处,1表示Male的事实仅存在于New操作中。在其他任何地方,您都必须重复这一逻辑(这会引入错误的机会,例如男性10)。此外,如果您决定更改这些值,则必须记住在任何地方更改它们。如果你想使用整数id,那么你应该在某处抽象出意义,无论是enum,静态类,数据库表等。更好的选择是保持字符串,并使用下拉列表来强制执行规范化该字符串值。

public string CustomerGender { get; set; }

public IEnumerable<SelectListItem> CustomerGenderChoices
{
    get
    {
        return new List<SelectListItem>
        {
            new SelectListItem { Value = "Male", Text = "Male" },
            new SelectListItem { Value = "Female", Text = "Female" }
        }
    }
}

然后,在您看来:

@Html.DropDownListFor(m => m.CustomerGender, Model.CustomerGenderChoices, "Select Gender", new { @class = "form-control" })

或者,如果你要使用枚举:

public enum Genders
{
    Male = 1,
    Female = 2
}

然后,在您的视图模型中,您只需要一个属性,只需存储值:

public Genders CustomerGender { get; set; }

然后,在您看来,您可以使用EnumDropDownListFor

@Html.EnumDropDownListFor(m => m.CustomerGender, "Select Gender", new { @class = "form-control" })

作为枚举,存储的值将是一个int,但这里的好处是这些整数值与它们的含义之间存在强类型关联。例如,而不是做类似的事情:

if (customer.CustomerGender == 1) // Male

你可以这样做:

if (customer.CustomerGender == Genders.Male)

显然,第二个版本的意义更为明显。

相关问题