Kevin
Kevin

Reputation: 198

Passing values of checkboxes from View to Controller

I have a view with a number of checkboxes in it. I want to be able to pass the values of the checkboxes to the controller, then output a list of the OfficeNames that have been ticked. I am not sure how to pass the values of multiple checkboxes back to the controller, or how to output the OfficeNames based on which boxes have been ticked

View:

<p>
@using (Html.BeginForm())
{
<p>
    Start Date: @Html.TextBox("StartDate") <br />
    <br />
    End Date: @Html.TextBox("EndDate") <br />
    <br />
    <input type="submit" value="Filter" />
</p>
}

<p>
@foreach (var item in Model.BettingOffices)
{
    <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
    <input type="checkbox" name="selectedShops" value="@item.OfficeName">
}

</p>

Controller:

public class DailyReportController : Controller
{
    private RiskEntities _db = new RiskEntities();

    // GET: /DailyReport/
    public ActionResult Index(DateTime? startDate, DateTime? endDate)
    {

        if (startDate == null || endDate == null)
        {
            var dailyReportModelBlank = new DailyReportModel();
            dailyReportModelBlank.BettingOffices = (from bo in _db.BettingOffices orderby bo.OfficeName select bo ).ToList();
            //dailyReportModelBlank.DailyReports.Add(new DailyReport());
            return View(dailyReportModelBlank);
        }

        var endDateToUse = (DateTime) endDate;
        endDateToUse = endDateToUse.AddDays(+1);


        var dailyReportModel = new DailyReportModel
        {
            DailyReports = (from dr in _db.DailyReports
                where dr.DailyReportDate >= startDate
                      && dr.DailyReportDate <= endDateToUse
                select dr).ToList(),
            BettingOffices = (from bo in _db.BettingOffices select bo).ToList()
        };


        return View(dailyReportModel);
    }

Model:

public class DailyReportModel
{
    private List<DailyReport> _dailyReports = new List<DailyReport>();
    private List<BettingOffice> _bettingOffices = new List<BettingOffice>();

    public List<DailyReport> DailyReports
    {
        get { return _dailyReports; }
        set { _dailyReports = value; }
    }

    public List<BettingOffice> BettingOffices
    {
        get { return _bettingOffices; }
        set { _bettingOffices = value; }
    }
}

BettingOffice Class:

public partial class BettingOffice
{
    public int BettingOfficeID { get; set; }
    public string OfficeName { get; set; }
    public string OfficeCode { get; set; }
    public string IpAddress { get; set; }
    public Nullable<bool> SupportOnly { get; set; }
    public Nullable<int> SisSrNumer { get; set; }
    public Nullable<bool> Local { get; set; }
    public string Server { get; set; }
}

Upvotes: 4

Views: 44052

Answers (6)

kamalkishor nagawade
kamalkishor nagawade

Reputation: 21

View:

@using (Html.BeginForm("Createuser", "User", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>


    <div class="form-group">
        @Html.LabelFor(m => m.city, new { @class = "col-md-2 control-label" })
    </div>
    <div class="col-md-10">
        <table>
            <tr>
                <td><input type="checkbox" name="city" value="Pune" id="1" />Pune</td>
                <td><input type="checkbox" name="city" value="Banglore" id="2" />Banglore</td>
                <td><input type="checkbox" name="city" value="Mumbai" id="3" />Mumbai</td>
            </tr>
        </table>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" class="btn btn-default" value="Create" />
            </div>
        </div>
        }


        [HttpPost]
        public ActionResult Createuser(user user, string [] city)
        {
            var UserInfo = new user 
           { Email =user.Email,Password=user.Password,Firstname=user.Firstname };                 
            return View();
        }

Upvotes: 2

BJ Patel
BJ Patel

Reputation: 6278

Try the following

your View is:

@foreach (var item in Model.BettingOffices)
{
    <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
    <input type="checkbox" name="selectedShops" value="@item.OfficeName">
}

Controller

[HttpPost]
public ActionResult Index(FormCollection collection)
{
     if(!string.IsNullOrEmpty(collection["selectedShops"]))
     {
        string strSelectedShops = collection["selectedShops"];        
     }
}

Upvotes: 0

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61509

Few things that need to change here.

  1. If you want values to be passed to action method they need to be within form not outside

  2. For MVT to 'understand' checkbox values as array (or more complex object) you need to work with their html name attribute.

I will do demonstration application below that should help you understand how it works:

CsHtml: Notice that you need to add value attribute to checkboxes to be able to read their values, checkbox gets true only when checkbox is ticked and value is true, hence the javascript. You can add as many of complex object properties as hidden fields as long as you give them names that match to the object property names in viewModel. In this case I am only passing BettingOfficeID

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).on("click", "[type='checkbox']", function(e) {
    if (this.checked) {
        $(this).attr("value", "true");
    } else {
        $(this).attr("value","false");}
});

<p>
    @using (Html.BeginForm())
    {
        <p>
            Start Date: @Html.TextBox("StartDate") <br />
            <br />
            End Date: @Html.TextBox("EndDate") <br />
            <br />
        </p>

        <p>

            <input type="checkbox" name="BettingOffices[0].Selected" value="true">
            <input type="hidden" name="BettingOffices[0].BettingOfficeID" value="1">

            <input type="checkbox" name="BettingOffices[1].Selected" value="false">
            <input type="hidden" name="BettingOffices[1].BettingOfficeID" value="2">

            <input type="checkbox" name="BettingOffices[2].Selected" value="true">
            <input type="hidden" name="BettingOffices[2].BettingOfficeID" value="3">

            <input type="checkbox" name="BettingOffices[3].Selected" value="false">
            <input type="hidden" name="BettingOffices[3].BettingOfficeID" value="4">

            <input type="checkbox" name="BettingOffices[4].Selected" value="true">
            <input type="hidden" name="BettingOffices[4].BettingOfficeID" value="5">
        </p>

        <input type="submit" value="submit"/>
    }

Post Action method to add to controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(BettingViewModel viewModel)
    {
        return null;
    }

BettingViewModel: I have added Selected property to BettingOffice class.

public class BettingViewModel
{
    public string StartDate { get; set; }

    public string EndDate { get; set; }

    public List<BettingOffice> BettingOffices { get; set; }

}

public class BettingOffice
{
    public bool Selected { get; set; }
    public int BettingOfficeID { get; set; }
    public string OfficeName { get; set; }
    public string OfficeCode { get; set; }
    public string IpAddress { get; set; }
    public Nullable<bool> SupportOnly { get; set; }
    public Nullable<int> SisSrNumer { get; set; }
    public Nullable<bool> Local { get; set; }
    public string Server { get; set; }
}

enter image description here

Hope this saves you some time.

Upvotes: 2

user3804034
user3804034

Reputation:

try this :

<p>
    @using (Html.BeginForm())
    {
        <p>
            Start Date: @Html.TextBox("StartDate")
            <br />
            <br />
            End Date: @Html.TextBox("EndDate")
            <br />
            <br />
            <input type="submit" value="Filter" />
        </p>
    }
</p>
<p>
    @foreach (var item in Model.BettingOffices)
    {
        <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
        <input type="checkbox" name="bettingOfficeIDs" value="@item.BettingOfficeID">
    }
</p>

And in your Action you can get the selected office ids in bettingOfficeIDs variable:

 public ActionResult YourActionName(int[] bettingOfficeIDs)

Upvotes: 10

Vikram Singh Saini
Vikram Singh Saini

Reputation: 1887

1. First of all, you are generating checkboxes with same name. So how you will be able to retrieve them on server end separately?

So declare some counter that gets incremented and name checkboxes uniquely.

@foreach (var item in Model.BettingOffices)
{
    int counter=1;
    var checkboxName = "selectedShops" + counter;

    <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
    <input type="checkbox" name="@checkboxName" value="@item.OfficeName">

    counter++;
}

2. Now on submission of Form in your controller, get checkboxes as -

//Loop through the request.forms
for (var i = 0; i <= Request.Form.Count; i++)
{
   var checkboxValue = Request.Form["selectedShops[" + i + "]"];

   // Do whatever you want to with this checkbox value
}

For ticked values, you will probably get True value. Debug the retrieved value to write further code accordingly.

Upvotes: 0

Hi you can get the selected checkbox value using the bellow code it seem working fine fore me,

<script>
$(document).ready(function()
{
    $("input[type=checkbox]").click(function()
    {
            var categoryVals = [];
            categoryVals.push('');
            $('#Category_category :checked').each(function() {
          categoryVals.push($(this).val());
        });
        $.ajax({
            type:"POST",
            url:"<?php echo $this->createUrl('ads/searchresult'); ?>", //url of the action page
            data:{'category': categoryVals},
            success : function(response){
               //code to do somethng if its success
            } 
            });
    }
}
</script>

Upvotes: -1

Related Questions