skip to Main Content

I am having trouble passing data from my view to my controller. I am using checkboxes. For my view, I created a class that takes in all my checkboxes (Mon-Fri) and putting them into a list (so I can use the data someplace else). My problem is that when I debug and click the checkboxes on the website, the code does not change whether I click the checkbox or not, so my code doesn’t recognize the checkbox data

I’m not sure if I have implemented the View incorrectly but any help to the right direction would be appreciated !

ViewModel:

public List<cDay> _cDays = new List <cDay>();

public List<cDay> cDays
{
   get {return _cDays;}
   set {_cDays = value;}
}

public class cDay
{
    public bool Monday { get; set; }
    public bool Tuesday { get; set; }
    public bool Wednesday { get; set; }
    public bool Thursday { get; set; }
    public bool Friday { get; set; }
}

CSHtml file:

@Html.Label("M")
@Html.CheckBox("Monday", false, new { @class = "availability" })
// this is basically the same code for Tuesday-Friday as well.

'<label for="M">M</label> +
'<input class="availability" id="Monday" name="Monday" type="checkbox" value="true">' +
'input name="Monday" type="hidden" value="false">'
// this is basically the same code for Tuesday-Friday, but the "name" corresponds to each day

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string inputValue, Model viewModel)
{
    if(ModelState.IsValid)
    // 

}

2

Answers


  1. Consider to use the following data model:

    public class DaysViewModel  
    {
        public List<CDay> Days { get; set; } = new List<CDay>();
    }
    
    public class CDay
    {
        public CDay()
        {
            Name = string.Empty;
            Selected = false;
        }
    
        public CDay(string name) 
        {
            Name = name;
            Selected = false; 
        }      
    
        [Required]
        public string Name { get; set; }
        [Required]
        public bool Selected { get; set; }
    }
    

    Then you can use the default ASP.NET MVC data binding without a JS support:

    @model Models.DaysViewModel
    
    @using (Html.BeginForm("Edit", "Home"))
    {   
        @Html.AntiForgeryToken() 
        for(int i=0; i < Model.Days.Count; i++)  
        {
            <div class="form-group row">
            @Html.CheckBox("Days[" + i + "].Selected", Model.Days[i].Selected)   
            @Html.Hidden("Days[" + i + "].Name", Model.Days[i].Name)
            <span>@Model.Days[i].Name </span>   
            </div>
        }
        <input type="submit" value="Save" />
    }
    

    And on the server side:

    public ActionResult Edit()
    {
        var model = new DaysViewModel();
        model.Days.AddRange( new List<CDay> {
                new CDay("Monday"),
                new CDay("Tuesday"),
                new CDay("Wednesday"),
                new CDay("Thursday"),
                new CDay("Friday")
            });
        return View(model);
    }
    
    [HttpPost]        
    [ValidateAntiForgeryToken]
    public ActionResult Edit(List<CDay> days)
    {
        if(ModelState.IsValid)
        {
            // ... you_code here 
        }
        var model = new DaysViewModel() { Days = days };
        return View(model);
    }
    

    Test screen shots

    The view:

    enter image description here

    On the controller side:

    enter image description here

    Login or Signup to reply.
  2. You can do it using jQuery

    Add a button bellow your checkboxes

    <input type="button" value="Your_Value" class="btn btn-default" />

    When click on a button create a post request and sends checked status via querystring

    $(document).ready(function () {
        $("input[type=button]").click(function () {
            var queryString = 'Monday=' + $("input[name=Monday]").is(":checked") + '&Tuesday=' + $("input[name=Tuesday]").is(":checked") + '&Wednesday=' + $("input[name=Wednesday]").is(":checked") + '&Thursday=' + $("input[name=Thursday]").is(":checked") + '&Friday=' + $("input[name=Friday]").is(":checked");
            $.ajax({
                type: "Post",
                url: "/Home/Edit?" + queryString,
                success: function (data) {
                },
                error: function (data) {
                }
            });
        });
    });
    

    And inside controller create Edit Post Method like this

    [HttpPost]
    public ActionResult checkboxespost(string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
    {
        ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search