Home Checkbox value always 0 after insert into database
Reply: 0

Checkbox value always 0 after insert into database

user8197
1#
user8197 Published in September 19, 2018, 6:44 pm

I am building a website using Asp.Net MVC. I have successfully inserted my form data into the database. However, I got a problem with my checkbox, the value is always 0 in my database even if the checkbox is checked.

@using (Html.BeginForm())
{
    <div class="modal-body">
        <div class="form-group">
            <label for="username" class="col-form-label">Name:</label>
            <input type="text" class="form-control" **id="username" name="username" **>
        </div>
        <div class="row">
            <div class="form-group">
                <div class="col-md-6">
                    <input type="checkbox" **id="user_privilage" name="user_privilage" **>
                    <label for="user" class="col-form-label">User</label>
                </div>
            </div>
        </div>
    </div> 
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Add</button>
    </div>
}

here is the code in controller:

[HttpPost]
public ActionResult UserMaintenance(User collection)
{
    try
    {
        List<object> lst = new List<object>();
        lst.Add(collection.username);
        lst.Add(collection.user_privilage);
        object[] allitems = lst.ToArray();
        int output = db.Database.ExecuteSqlCommand("insert into DATABASE(username,user_privilage) values (@p0,@p1)", allitems);
        if(output>0)
        {
            ViewBag.msg = "User has been added";
        }
        return View();
        //return RedirectToAction("UserMaintenance");
    }
    catch {
        return View();
    }
}

Does anyone know what happened?

share|improve this question
  • Always use view models – Mindless Nov 10 '17 at 1:39
  • You not giving the checkbox a value (so it posts back "on" if its checked). Use a view model with a bool property and strongly bind to your model with @Html.CheckBoxFor(m => m.yourProperty) and ditto for all your controls – Stephen Muecke Nov 10 '17 at 1:43

1 Answer 1

active oldest votes
up vote 0 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296068 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO