将枚举值传递给控制器​​。来自模特?

时间:2017-08-21 01:28:13

标签: c# asp.net-mvc enums model

在我的Ggender控制器中,它说我无法隐式转换类型'String',请提供建议。

我的模特:

public class StaffRegistrationViewModel : IValidatableObject
    {
        [Required(ErrorMessage = "Please select your gender.")]
        public Gender? GGender
        { get; set; } //= null;

        public enum Gender
        {
            [Display(Name = "Male", Order = 0)]
            Male = 0,

            [Display(Name = "Female", Order = 1)]
            Female = 1

        }

我的观点:

    <div class="row">
        <div class="col-md-6">
            <!--<i class="fa fa-child" aria-hidden="true"></i>-->
            @Html.LabelFor(model => model.GGender, "Choose your gender:", new { @style = "", @class = "", id = "" })
            <span style="color: red;">*</span>
            @*@Html.DropDownListFor(model => model.Profession, new SelectList(Model.Professions, "Id", "Name"), new { placeholder = "", @style = "", @class = "form-control", id = "Profession" })*@
            @Html.EnumDropDownListFor(model => model.GGender, "Please select", new { @class = "form-control" })


            @Html.ValidationMessageFor(model => model.GGender)
        </div>

控制器:

StaffRegistrationViewModel StaffRegistrationViewModel = new StaffRegistrationViewModel();

StaffRegistrationViewModel.GGender = HttpContext.Request.Form["GGender"].ToString(); //cannot implicitly convert type 'String'

1 个答案:

答案 0 :(得分:0)

您可以声明一个字符串变量来保存Request.Form内容&amp;在switch语句中使用它,而不是直接将字符串值赋给枚举变量:

string gender = HttpContext.Request.Form["GGender"].ToString();

switch (gender)
{
    case "Male":
        StaffRegistrationViewModel.GGender = Gender.Male;
        break;

    case "Female":
        StaffRegistrationViewModel.GGender = Gender.Female;
        break;

    // you can default to null value for nullable enum properties if you want
    default:
        StaffRegistrationViewModel.GGender = null;
        break;
}

请注意,HttpContext.Request.Form将提交的值存储为字符串,因此如果要直接返回枚举值,只需使用控制器操作方法中的viewmodel名称来传递提交的值(并在视图页中使用模型指令,例如{{1 }}):

@model StaffRegistrationViewModel

注意:您可以为与[HttpPost] public ActionResult StaffRegistration(StaffRegistrationViewModel model) { // other logic here // enum assignment example Gender? gender = model.GGender; // other logic here return View(model); } 绑定的枚举编写自定义模型绑定器,如此参考中所述:How does one perform asp.net mvc 4 model binding for enums?