views:

119

answers:

2

Hello everybody,

can I use it like this in View?

<%= Html.CheckBoxFor(user => user.Role, "Administrator")%>

and then just read a value of property in model if checkbox is checked:

string role = user.Role;
(role = "Administrator")

Help me please!

Take care, Ragims

A: 

Checkboxes are read as "true" or "false", that is they are a boolean type. What you can do is have a viewmodel with a IsAdmin property and then check in your controller if the property is true.

// View
<%: Html.CheckBoxFor(model => model.IsAdmin)

// Controller
If(viewModel.IsAdmin)
{
    doYourStuff();
}
JoseMarmolejos
Thank you, very helpfull!!
Ragims
+1  A: 

In your model...

public class UserEditModel { 
  public string UserName { get; set; }
  public string[] Role { get; set; }
}

In your view...

<%: Html.TextBoxFor(x = x.UserName)<br />
<input type="checkbox" name="role" id="role_Administrator" value="Administrator" />
<input type="checkbox" name="role" id="role_Create_Project" value="Create Project" />
<!-- etc -->

Yes, you need to write raw HTML for this scenario. This will bind correctly with the MVC defaults. The default CheckBoxFox really only works well with True/False bindings. Something like

<%: Html.CheckBoxFor(x => x.AcceptLicenseTerms) %>

or

<%: Html.CheckBoxFor(x => x.RememberMe) %>
Jarrett Meyer
Thank you, very helpfull!!
Ragims
@Ragims: If it was very helpful and it answered your question, you should consider marking his solution as answered.
Scott Lance
sorry i am a bit confused what i all have here to do. thanks for introduction:)!
Ragims
I think this particular scenario (your code) is better fit for a radio-button group type of choice selection.
JoseMarmolejos
I want to make dropdownlist with ability to add new role, thatsway i need to use check box i think it makes more sense or??
Ragims