0

In my project I have a string field in the view model to display in a form and post back to the controller.

However for some reason, I'd like to display a checkbox, and retrieving string "True"/"False" from user input

I've searched through the internet and found this How to render a model property of string type as checkbox in ASP.NET MVC which leverage the editor template and achieve my need.

My question is that how do this be achieved, because in the editor template, I can only see it how to interpret the string to a checkbox, but it never explain or show how the checkbox value will be bind back to the string field with "True"/"False".

What should I do if I wanted "Yes"/"No" instead of "true"/"false", are there any converter that I need to make to parsing the checkbox to string?

Sorry for my bad English and lack of mvc knowledge, I just started MVC and web development for a few days.

UPDATE: 1. I am using ViewModel to bind with the forms, so I need something like Html.CheckBoxFor(x=>x.value) while x.value is a string, obviously it is not possible with the default CheckboxFor

Community
  • 1
  • 1
RCheung
  • 11
  • 3

1 Answers1

1

I think what you are asking is how to save the value back into your database, which is more of a back-end C# or VB question.

As you know, when you submit a form on an HTML page, if a checkbox is ticked, it's value will be passed in the POST parameters back to the server:

front-end HTML:

<input type="checkbox" name="theCheckBox" value="Yes" />

back-end C# in Page_Load() or similar

if(Request.Form["theCheckBox"] == "Yes") {
    // save value "Yes" into database
}

just remember that if the checkbox is NOT TICKED, Request.Form["theCheckBox"] will be null

Matt Kemp
  • 2,742
  • 2
  • 28
  • 38
  • Thanks for you answer, but since I am binding to a ViewModel, I'd like to have the value bind to the field with string property. – RCheung Nov 21 '12 at 04:48
  • Sorry Matt, I've pasted a wrong link that I referenced before. Take a look at this one, I'm using the answer in this thread, but I am not very understand what is happening behind the scene for binding. http://stackoverflow.com/questions/7203583/how-to-render-a-model-property-of-string-type-as-checkbox-in-asp-net-mvc – RCheung Nov 21 '12 at 04:55