How to pick up Radiobuttonfor value through Formcollection and save to SQL Server BD

Asked

Viewed 563 times

0

I have a model with several booleans, I need to take their values through a Formcollection and save in the SQL database (does not accept Boolean, so the field is as 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 mounting control for 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;
            }  
  • Dude, you should seriously think about giving up the use of FormCollection in order to use a typed object.

1 answer

2


The conversion of Boolean for bit is transparent. I don’t know how your process is, but if the parameter @sex is a bit, this statement:

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

Works smoothly.

This approach is not at all correct. In its place, I would define a Enum for Sex:

public enum Sex {
    Male, 
    Female
}

The Model would have a column with the type Sex:

public Sex Sex { get; set; }

The View then 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.