How can i return radiobutton selected value within extended idenity model within

102 Views Asked by At

I am new to ASP.net MVC. I am stucked right now. i extended the identity model to include bio data like firstName, LastName, Gender etc.

I want to have the Gender rendered as radio button, I am able to run app without any error, but it will not submit the registration. This issue started after i change the gender from textbox to radio button. here is my code.

Part of my model:

    [Display(Name = "Middle Name")]
    [MaxLength(25)]
    public string MiddleName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    [MaxLength(25)]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "Gender")]
    public string Gender { get; set; }

My controller:

 public async Task<ActionResult> Register(RegisterViewModel model)
    {
    if (ModelState.IsValid)
        {


            var member = new MemberInformation
            {
                Id =
                    Guid.NewGuid().ToString() + DateTime.Now.Year +             DateTime.Now.Month + DateTime.Now.Day +
                    DateTime.Now.Hour,
                FirstName = model.FirstName,
                LastName = model.LastName,
                MiddleName = model.MiddleName,
                Gender = model.Gender,
                ContactAddress = model.ContactAddress,
                MarialStatus = model.MarialStatus,
                Occupation = model.Occupation,
                MobilePhone = model.MobilePhone,
                RegistrationDate = DateTime.Now,
         }

my view:

    <div class="form-group">
    @Html.LabelFor(m => m.Gender, new {@class = "col-md-2 control-label",})
    <div class="col-md-10">
        @Html.LabelFor(m => m.Gender, "Male")
        @Html.RadioButtonFor(Model => Model.Gender,  "Male") 
        @Html.LabelFor(m => m.Gender, "Female")
        @Html.RadioButtonFor(m => m.Gender,  "Female")
      </div>
     </div>
2

There are 2 best solutions below

0
Jean-Bernard Pellerin On

I suspect your Model => Model.Gender expression is causing some confusion because Model already means something in that scope.

LabelFor is also odd when used that way, use an html label to simplify things

    <label>@Html.RadioButtonFor(m => m.Gender, "Male")Male</label>
    <label>@Html.RadioButtonFor(m => m.Gender, "Female")Female</label>
3
Erresen On

When you use Html.RadioButtonFor the same model property twice it creates two controls with the same ID. As the postback only cares about names, not IDs, you need to override the IDs, as below:

@Html.RadioButtonFor(m => m.Gender, "Male", new {id = "GenderMale"})
@Html.RadioButtonFor(m => m.Gender, "Female", new { id = "GenderFemale" }) 

This creates radiobuttons that map to Gender, but with different IDs.

Note - you should include the new { id = "Whatever" } bit, otherwise it'll duplicate IDs again.