How to get RadioButtonFor value through FormCollection and save in BD SQL Server

0

I have a model with several booleans, I need to get their values through a FormCollection and save them to the SQL database (it does not accept boolean, so the field is a bit).

My View:

<div class="editor-field">
            @Html.RadioButtonFor(model => model.Sex,"false", false)F
            @Html.RadioButtonFor(model => model.Sex,"true", true)M               
</div>

Action:

public ActionResult Create(FormCollection form)
        {
            var pSimpleUser = new SimpleUserr()
            {
                IdSimpleUser = 0,                    
                Sex = Convert.ToBoolean (form["sex"]),
            };
            if (ModelState.IsValid)
            {
                using (SimpleUserDAO dao = new SimpleUserDAO())
                    if (dao.SaveSimpleUser(pSimpleUser))
                    {
                        ViewBag.AlertMessage = "Salvo Com Sucesso";
                        return View();
                    }
            }
            ViewBag.AlertMessage = "Ocorreu um problema ao salver";
            return View(pSimpleUser);
        }

    }
}

Function with the command assembly for the Procedure:

    public bool SaveSimpleUser(SimpleUserr pSimpleUser)
            {
                if (pSimpleUser !=null)
                {
                    using (_context)
                    {
                        SqlCommand cmd = new SqlCommand("SaveSimpleUser");
                        cmd.Parameters.AddWithValue("@idSimpleUser", pSimpleUser.IdSimpleUser);                        
                        cmd.Parameters.AddWithValue("@sex", pSimpleUser.Sex);
pSimpleUser.IsPaceMaker);
                        cmd.CommandType = CommandType.StoredProcedure;
                        this._context.ExecuteProcedure(cmd);
                        return true;
                    }
                }
                return false;
            }  
    
asked by anonymous 16.05.2014 / 21:36

1 answer

2

Conversion from Boolean to bit is transparent. I do not know how your procedure is, but if the parameter @sex is a bit , this statement:

cmd.Parameters.AddWithValue("@sex", pSimpleUser.Sex);

It works without problems.

This approach is not entirely correct. In its place, I would set Enum to Sex :

public enum Sex {
    Male, 
    Female
}

The Model would have a column with type Sex :

public Sex Sex { get; set; }

View would look like this:

<div class="editor-field">
        @Html.RadioButtonFor(model => model.Sex, Enums.Sex.Female) Female
        @Html.RadioButtonFor(model => model.Sex, Enums.Sex.Male) Male
</div>

And the parameterization of procedure would be:

cmd.Parameters.AddWithValue("@sex", (int)pSimpleUser.Sex);
    
16.05.2014 / 22:15