views:

158

answers:

1

Hello all, this is closely related to a question I posted yesterday regarding checkboxes.

Here is my setup:
-I have a database directory, with a list of names, among other fields, as my model.

-I have a search page where users can search this directory and select a name.

-I have a form page that displays the name with a checkbox next to it which allows the user to decide if they want to include the name as a value in the submitted form.

-A controller that handles the submitted form.

Goal:
-What I would like to know is how can I get the string value of the name that was selected in the directory to both display in the form page View and also include this string in the value field of the checkbox??

A: 

You cannot change what the value of a checked check box; check boxes always get posted with "on" as their values if checked, and MVC can use this to automatically map the posted values to booleans. However, if this list of names is dynamic, and each name is unique, you can generate the form with dynamically-named check boxes. Then, in the controller, you can inspect the raw form to see which names were checked. For example, in the view, your code could look something like this:

<form>
  <% /* Some loop here */ { %>
    <input type="checkbox" name="name_<%= Html.Encode(theName) %>" /> 
    <label><%= Html.Encode(theName) %></label>
  <% } %>
</form>

Then, in the controller:

foreach (string name in listOfAvailableNames)
{
    if (Request.Form["name_" + name] == "on")
    {
        // Handle the name being selected
    }
    else
    {
        // Handle the name not being selected
    }
}
Jacob
Whoever it is that down-voted, please explain why.
Jacob