Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Mvc 2 Checkbox always false in model

Tags:

asp.net-mvc

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.

like image 616
sharp johnny Avatar asked Nov 05 '22 07:11

sharp johnny


2 Answers

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..

like image 77
Will Avatar answered Nov 11 '22 16:11

Will


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) %>
like image 35
Nick Bork Avatar answered Nov 11 '22 14:11

Nick Bork