sharp johnny
sharp johnny

Reputation: 814

Asp.Net Mvc 2 Checkbox always false in model

I have a checkbox like this:

<%= Html.CheckBoxFor(x => x.IsSendingQualitySurvey) %>/>

when checking the checkbox and submitting, I get the typical 2 form values:

IsSendingQualitySurvey: true
IsSendingQualitySurvey: false

This is perfectly valid for the way the mvc modelbinder handles checkboxes.

Then in the controller action:

[HttpPost]
public ActionResult Edit(Guid id, TicketEditViewModel ticketEditViewModel)

ticketEditViewModel.IsSendingQualitySurvey (a normal bool) is always false.

I don't have any custom model binders and it works elsewhere. Strangely enough I've had the same problem in another view quite a while ago, where I had to create the input manually, looks like this:

<input type="checkbox" value="true" name="<%=Html.NameFor(x => x.IsRequestingVisit) %>" id="<%=Html.NameFor(x => x.IsRequestingVisit) %>" />

This worked, but when I copied the exact same over to the other view, the value is still always false.

Wheres the catch?

Thanks.

Upvotes: 5

Views: 4355

Answers (4)

Yulian
Yulian

Reputation: 6759

I'm not sure whether this will work for you, but in fact it solved the same issue for me. Try adding (not replacing) a hidden field for the same model's property like this:

@Html.HiddenFor(x => x.IsSendingQualitySurvey)

Upvotes: 0

knowwebapp.com
knowwebapp.com

Reputation: 95

For following model:

public class StartViewModel {

public string Id{ get; set; }

public string Name { get; set; }

public bool Accept { get; set; }

}

-> Accept =false.

The solution: Change public bool Accept { get; set; } to public string Accept { get; set; }

When submit, if checkbox is checked, The "Accept" value = "on". You can dectect checked value by the way.

Upvotes: 0

Nick Bork
Nick Bork

Reputation: 4841

The model binder likely wont pickup the binding. My advice is to change your action to:

 [HttpPost] 
 public ActionResult Edit(Guid id, TicketEditViewModel model)

The model binder wants to find properties in the Request that have a prefix that match your object name. Since there is no naming prefix on the client side, there are no properties with the prefix "ticketEditViewModel".

The alternative is to name a variable on the page:

 <% var ticketEditViewModel = Model; %>
 <%= Html.CheckBoxFor(model => ticketEditViewModel.IsSendingQualitySurvey) %>

Upvotes: 1

Will
Will

Reputation: 481

EDIT Got the wrong end of the stick... sorry

Have you tried fetching the raw value out of the post data like so:

In the Controller:

[HttpPost]
public ActionResult Edit(Guid id, TicketEditViewModel ticketEditViewModel,
                                            FormCollection fc) {

    if(fc["IsSendingQualitySurvey"].Contains("true")) {
        //Do something.
    }
}    

In the View:

<%= Html.CheckBoxFor(model => model.IsSendingQualitySurvey) %>

Hope this helps..

Upvotes: 1

Related Questions