Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Checkbox value won't clear

I have a fairly straightforward razor view which needs to be used for a questionnaire, which is used repeatedly until it runs out questions. Checkbox is used for select answers, the problem is when I first submit the form when the next set of questions returned the answers I submit in the first time are retained in the second page. For the simplicity I have reduced the program as follows,

Model,

public class CheckBoxItemDto
{
    public int Id { get; set; }

    public bool Selected { get; set; }
}

public class CheckBoxModel
{
    public CheckBoxModel()
    {
        Dtos = new List<CheckBoxItemDto>();
    }

    public IList<CheckBoxItemDto> Dtos { get; set; }
}

Controller,

public class CheckBoxController : Controller
{
    public ViewResult Index()
    {
        CheckBoxModel model = new CheckBoxModel();
        for (int i = 0; i < 5; i++)
        {
            model.Dtos.Add(new CheckBoxItemDto(){Id = i,Selected = true});   
        }
        return View(model);
    }

    [HttpPost]
    public ViewResult Index(CheckBoxModel mdl)
    {
        CheckBoxModel model = new CheckBoxModel();
        for (int i = 5; i < 10; i++)
        {
            model.Dtos.Add(new CheckBoxItemDto() { Id = i, Selected = i % 2 == 0 });
        }
        return View(model);
    }
}

View,

@model CheckBoxTest.Models.CheckBoxModel

@{
    ViewBag.Title = "ViewPage1";
}

<h2>ViewPage1</h2> 
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Dtos.Count; i++)
{
    @Html.DisplayFor(m => m.Dtos[i].Id)
    @Html.DisplayFor(m => m.Dtos[i].Selected)
    @Html.CheckBoxFor(m => m.Dtos[i].Selected)
    <br/>
}
<input type="submit" value="Index" /> 
}  

In the view after post, DisplayFor and CheckBoxFor column values are different. But It should be the same.

like image 442
Low Flying Pelican Avatar asked Nov 22 '25 23:11

Low Flying Pelican


2 Answers

By the sound of it your ModelState is still holding its previous values when you return the view. Try clearing the ModelState in your post action:

ModelState.Clear();
CheckBoxModel model = new CheckBoxModel();
...
like image 102
Dangerous Avatar answered Nov 25 '25 13:11

Dangerous


In your Index action method that gets run for a POST, ASP.Net MVC is expecting the resulting View to display validation errors. Therefore, the HTML Helper method CheckBoxFor looks in the ModelState before the Model, so it can display the "invalid" value to the user.

If you're not using the View from a POST action to display errors, you can clear the ModelState as Dangerous suggests. Or, you could use the "Post-Redirect-Get" pattern: in your POST action method, display the same View if there are errors, or else redirect to a GET view that displays something else.

like image 23
Graham Clark Avatar answered Nov 25 '25 12:11

Graham Clark