简体   繁体   中英

How to create a list with Male and Female from model to view

I want a drop-down list for gender which may get value as enum but can submit value in a string format.

I have the following model:

public partial class User
    {
        public Gender gender { get; set; }
        //public string gender { get; set; }
        public enum Gender
        {
            Male,
            Female
        }
    }

I have the following view:

@using (Html.BeginForm())
{
<div class="form-horizontal">
    <div class="form-group">
        <p class="control-label col-md-2"><label for=model.gender>Gender</label></p>
        <div class="col-md-10">
          @Html.DropDownListFor(m => m.gender, new SelectList(Enum.GetValues(typeof(Gender))), "Select Gender")
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>
}

I have the following controller:

[HttpPost]
public ActionResult Register(User us)
{
        tourEntities tp = new tourEntities();
        tp.Users.Add(us);
        tp.SaveChanges();
        return View();
}

solved problem had been in that line, replaced by this.

@Html.DropDownListFor(model => model.gender, new SelectList(Enum.GetValues(typeof(tour.Models.User.Gender))), "Select Gender")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM