0

Using Razor in my mvc web app.

I have this:

@Html.CheckBox(Model.SectionModel[i].PreferenceModel[j].Name,Boolean.Parse( Model.SectionModel[i].PreferenceModel[j].Value ))

so, for me here the initial value of this checkbox is TRUE.

Now, if my User sets it to false I wish to change/create a hidden field to show this value is FALSE for use in my postback.

I cannot use @HTML.CheckBoxFor because the value is coming from a XML file and this value could be for a different control that is not a boolean value.

Following the suggested answer route i put in this:

@Html.EditorFor( x => x.SectionModel[i].PreferenceModel[j].Value, Model.SectionModel[i].PreferenceModel[j].Name)

but the value as the value i string a textbox is rendered and not a checkbox. which is the opoosite to my problem

is null

Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179
  • Possible duplicate of [Getting Checkbox Value in ASP.NET MVC 4](http://stackoverflow.com/questions/14730746/getting-checkbox-value-in-asp-net-mvc-4) – demo May 23 '16 at 12:48
  • @demo will look and check that. thanks – Andrew Simpson May 23 '16 at 12:49
  • Accepted answer seems what You need – demo May 23 '16 at 12:50
  • @demo Hi, this is the opposite scenario to what I want. I have edited my question to explain. Thanks for the offering though.. :) – Andrew Simpson May 23 '16 at 13:05
  • 1
    why don't you try binding a click event in jQuery, and then handle it from script ? – Shanid May 23 '16 at 13:08
  • @Shanid Would you like to post an answer please? – Andrew Simpson May 23 '16 at 13:09
  • 2
    A `CheckBox()` (and `CheckBoxFor()`) is for binding to a bool, not a `string`. Use a view model with properties `string Value` and `bool IsSelected` and use `@Html.HiddenFor(m => m.SectionModel[i].PreferenceModel[j].Name)` and `@Html.CheckBoxFor(m => m.SectionModel[i].PreferenceModel[j].IsSelected)` –  May 24 '16 at 01:36
  • @StephenMuecke hi, yes I did it this way on the end. Thanks – Andrew Simpson May 24 '16 at 05:42

1 Answers1

1
$("#chkType").change(function (s, e) {
            if ($(this).is(":checked")) $("#hiddenField1").val('1');
            else $("#hiddenField1").val('0');
        });

This ought to work, I just copied it from one of my projects. Hope this helps. :)

Shanid
  • 557
  • 12
  • 30
  • Thanks will try in a minute. – Andrew Simpson May 23 '16 at 13:17
  • This makes no sense at all. A `CheckBox()` and `CheckBoxFor()` method is for binding to a bool, not an `int` or `string` and it will completely screw up model binding if you need to return the view –  May 24 '16 at 01:33
  • @StephenMuecke yes I agree. Your suggestion above was the way I did it in the end. I forgot to update this question as busy at work :) – Andrew Simpson May 24 '16 at 05:41
  • Sorry had to in tick this answer as the convertor on the model was a better approach for me – Andrew Simpson May 24 '16 at 05:42