MVC Checkbox value assigned in Model not same in another service page referencing the same model

Shri-6058 326 Reputation points
2022-04-07T09:03:17.867+00:00

This is a very interesting issue. After many iterations of multiple checkbox values due to hidden fields, I collect the values after string spilt etc and converting boolean. I am able to read/maintain the status of the checkbox within the HomeController page. However the same model I am referencing in another service project in the same solution doesnt reflect or maintain the same value. Any advise?
190844-untitled.jpg

Developer technologies ASP.NET Other
Developer technologies C#
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-04-07T10:17:30.297+00:00

    This question has been answered in your other thread(s)!

    This is a very interesting issue. After many iterations of multiple checkbox values due to hidden fields, I collect the values after string spilt etc and converting boolean. I am able to read/maintain the status of the checkbox within the HomeController page.

    Correct. You must write custom code if you do not use MVC's model binding with MVC's HTML helpers. I think the main issue is you do not understand how standard HTML checkbox inputs work. Therefore you do not understand why the HTML helper adds a hidden field. The hidden field is a very odd trick to force a default checkbox value if the use does not check a checkbox. The actual value is always the first item by name. Again, this information was explained in your other thread.

    However the same model I am referencing in another service project in the same solution doesnt reflect or maintain the same value. Any advise?

    You did not share the source code so we have no idea how the code works. I can only assume you are using standard model binding rather than the FormCollection.

    I recommend creating a test page with a checkbox to learn html checkbox fundamentals. Next create a test page to using the HTML.Checkboxfor and compare the differences.

    https://www.w3schools.com/tags/att_input_type_checkbox.asp

    0 comments No comments

  2. AgaveJoe 30,126 Reputation points
    2022-04-08T13:43:56.027+00:00

    I am currently able to postback mvc web controller and view. However I want to do the model binding for the mvc service application but the checkbox binding details wont come during runtime. Will you please advise?

    Your design does not follow MVC fundamental coding patterns. Unfortunately, there's a lot of problems with your code and general design. One example is setting a property after model binding takes place. The HTML helpers look at the model state which are the values passed to the action.

    The code example below focuses on the original subject which is maintaining the state of checkboxes and model binding.

    ViewModel

        public class TimeSheetViewModel  
        {  
            public TimeSheet TimeSheet { get; set; }  
        }  
      
        public class TimeSheet  
        {  
            public List<DailyList> DailyList { get; set; }  
        }  
      
        public class DailyList  
        {  
            public bool IsMealBreakWaived { get; set; }  
        }  
    

    Controller

     public class HomeController : Controller  
        {  
            [HttpGet]  
            public ActionResult Index()  
            {  
                TimeSheetViewModel model = new TimeSheetViewModel()  
                {  
                    TimeSheet = new TimeSheet()  
                    {  
                        DailyList = new List<DailyList> {   
                            new DailyList()  
                            {  
                                IsMealBreakWaived = true,  
                            },  
                            new DailyList()  
                            {  
                                IsMealBreakWaived = false,  
                            },  
                            new DailyList()  
                            {  
                                IsMealBreakWaived = true,  
                            },  
                            new DailyList()  
                            {  
                                IsMealBreakWaived = false,  
                            },  
                            new DailyList()  
                            {  
                                IsMealBreakWaived = true,  
                            },  
                            new DailyList()  
                            {  
                                IsMealBreakWaived = false,  
                            },  
                            new DailyList()  
                            {  
                                IsMealBreakWaived = true,  
                            },  
                        }  
                    }  
                };  
      
                return View(model);  
            }  
      
            [HttpPost]  
            public ActionResult Index(TimeSheetViewModel model)  
            {  
                return Json(model);  
            }  
      
        }  
    

    View

    @model MvcDemo.Controllers.TimeSheetViewModel  
      
    @{  
        ViewBag.Title = "Index";  
    }  
      
    <h2>Index</h2>  
      
    @using (Html.BeginForm())   
    {  
        @Html.AntiForgeryToken()  
          
    <div class="form-horizontal">  
        <h4>TimeSheetViewModel</h4>  
        <hr />  
        <div id="timesheet">  
            @for (int i = 0; i < Model.TimeSheet.DailyList.Count(); i++)  
            {  
                <div class="form-group">  
                    <div class="col-md-offset-2 col-md-10">  
                        @i: @Html.CheckBoxFor(m => Model.TimeSheet.DailyList[i].IsMealBreakWaived, new { @class = "missed" })  
                    </div>  
                </div>  
            }  
        </div>  
        <div id="results">  
            <ul>  
      
            </ul>  
        </div>  
    </div>  
    }  
    

    JavaScript/jQuery

    $(".missed").change(function () {  
        $.post("/Home/Index", $("form").serialize(), function (data) {  
            console.log(data);  
      
            $('#results ul').html('');  
            $.each(data.TimeSheet.DailyList, function (index, value) {  
                $('#results ul').append('<li>' + JSON.stringify(value) + '</li>')  
            });  
        });  
    });  
    

    The example is fairly basic. The view model is prepopulated and passed to the view. An AJAX post submits the entire HTML form each time a checkbox changes state. The post action return the form in JSON format. The JSON is written to the page so you can compare what's submitted to the state of the form.

    After fixing the design, if you still have state issues then there is something wrong with your data access or logic. I'm not a fan of submitting an entire collection of records when one record changes. I would submit only the record that changed not everything.

    Honestly, you should go through the getting started tutorials on this site. The tutorial has a checkbox example very similar to your design.

    Getting Started with Entity Framework 6 Code First using MVC 5


  3. Shri-6058 326 Reputation points
    2022-04-10T18:10:07.23+00:00

    I finally was able to pass the checkbox value to service by setting values while loading time function and I see it sets the IsMealWaived as “True” and show “Success” however the calculation process(or property set after model binding) overwrites or doesn’t execute.
    public WeekClass MealRestLoadTimeIntoWeek(string StartOfWeek, List<EXT_TIME> TheTimeList, List<DayClass> weekClass)
    {
    WeekClass TheWeek = new WeekClass();
    TheWeek.Start = Convert.ToDateTime(StartOfWeek);

                for (int x = 0; x < 7; x++)  //Day Loop  
                {  
                    DayClass TheDay = new DayClass();  
                    TheDay.TRAN_DATE = Convert.ToDateTime(TheWeek.Start).AddDays(x);  
                    TheWeek.DayList.Add(TheDay);  
                    foreach (EXT_TIME timeEntry in TheTimeList)    // loop thru each time entry per day  
                    {  
                        if (TheDay.TRAN_DATE == timeEntry.TRAN_DATE)  
                        {  
                            TheDay.TimeList.Add(timeEntry);     //Move the time entries accross one at a time     
      
                            for (int itr = 0; itr < weekClass.Count; itr++)  
                            {  
                                if (((TheDay.TRAN_DATE) == (weekClass[itr].TRAN_DATE)) && (weekClass[itr].IsMealBreakWaived))  
                                    TheDay.IsMealBreakWaived = true;  
                            }  
                        }  
                              
                    }  
                }  
                return TheWeek;  
            }  
      
    

    My execution starts here: As soon as checkbox is clicked, Meal Extra hour becomes ‘0’ (that means nothings should show) however it doesn’t calculate. If I hardcode date and set IsMealBreakWaived to True, it just works perfect now.
    191622-untitled.jpg

    foreach (DayClass Day in TheWeek.DayList){  
    if (Day.TRAN_DATE == DateTime.Parse("4/11/2022 12:00:00 AM"))  
     {        DayItem.IsMealBreakWaived = true;           }  
    }  
      
    

    I am able to dynamically get the checkbox values in CalculateMealsWaived.CS (service side calculation) however the final calculated value not displayed on the dashboard.
    191575-untitled1.jpg

    It also appears on actual Calculation rules->CalculateMealsWaived.cs and successfully execute it but some reason by the time it returns to controller and view, it turns into ‘false’.

    It looks like Design issue but I am passing as a separate form collection and force assigning model status etc.. Could you please advise where I am going wrong?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.