Parth Doshi
Parth Doshi

Reputation: 4208

Populating CheckBox in ASP.NET MVC from SQL Server

I am working on a ASP.NET MVC3 code to bind the CheckBoxes using the data from the column of my SQL Database present in App_Data directory.

My table SysUser3 contains two columns with values as follows:

 ProductName    ||        ProductId

  Pencil                    1
  Eraser                    2  
  Pen                       3  

Model:

public class StoreModel
{
    public List<ProductModel> Products { get; set; }
}

public class ProductModel
{
    public string ProductName { get; set; }
    public bool Selected { get; set; }
}

Controller:

    [HttpGet]
    public ActionResult CheckView()
    {
        var model = new StoreModel
        {
            Products = m.GetCheckBoxes()
        };

        return View(model);
    }

//GetCheckBoxes method()

    public IList<ProductModel> GetCheckBoxes()
    {
        IList<ProductModel> items = new List<ProductModel>();
        using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|DeveloperReport.mdf;User Instance=true"))
        {
            con.Open();

            string cmdString = "SELECT ProductName FROM SysUser3";
            using (SqlCommand cmd = new SqlCommand(cmdString, con))
            {
                using (SqlDataReader dataRead = cmd.ExecuteReader())
                {
                    while (dataRead.Read())
                    {
                        items.Add(new ProductModel
                        {

                            Text = dataRead["ProductName"].ToString()
                        });
                    }
                }
            }
        }
        return items;
    }

View:

     @using (Html.BeginForm())
     {

      <div>
        @Html.HiddenFor(x => x.ProductName)
        @Html.CheckBoxFor(x => x.Selected)
        @Html.LabelFor(x => x.Selected, Model.ProductName) 
      </div>

      }

However, my code isn't working fine and I am not able to see the binding taking place. I just get a empty checkbox when I run the code.

Can someone tell me what am I doing wrong

Thanks in advance

Upvotes: 2

Views: 3279

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

In your DAL you seem to be defining the item variable to be an List<ProductModel>() and inside the while clause you seem to be adding elements of type RoleModel to this list assigning only the Text property and not the Selected property which is what the checkbox is bound to. You seem to be selecting only the ProductName (SELECT ProductName FROM SysUser3).

There doesn't seem to be a Selected boolean column in your table, so you cannot populate properly this property and thus the generated checkbox in the view will never be checked.

I guess you will have to rethink your database design. But that's another topic.

As far as ASP.NET MVC is concerned, as long as you provide a valid view model to the view:

public ActionResult CheckView()
{
    var model = new StoreModel
    {
        Products = new[]
        {
             new ProductModel { ProductName = "product 1", Selected = true },
             new ProductModel { ProductName = "product 2", Selected = false },
             new ProductModel { ProductName = "product 3", Selected = true },
        }.ToList()
    };

    return View(model);
}

no matter where this data comes from, the corresponding checkboxes in the view will be properly bound:

@model StoreModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Products)
    <button type="submit">OK</button>
}

and in the corresponding editor template (~/Views/Shared/EditorTemplates/ProductModel.cshtml) which will be rendered for each element of the Products collection of your view model:

@model ProductModel
<div>
    @Html.HiddenFor(x => x.ProductName)
    @Html.CheckBoxFor(x => x.Selected)
    @Html.LabelFor(x => x.Selected, Model.ProductName) 
</div>

And then obviously you will have the corresponding POST action which will take your view model as argument and call the underlying DAL to do some processing:

[HttpPost]
public ActionResult CheckView(StoreModel model)
{
    // the model.Products collection will be properly bound here
    // with the values that the user selected in the form
    ...
}

Upvotes: 3

Related Questions