1

I have asp.net mvc 3 application. I have build the EDIT View which consist of different checkbox with same name and different value. I want to checked the checkbox by matching value of checkbox with the value in array of the string of c#.

Action:

public ActionResult Edit(int id)
{
    string[] AllRole = roleassign.Role.Split(',');
    ViewBag.allrole = AllRole;
    ViewBag.role = ivr.get_all_role();
    return View();
}

AllRole is array String consist of "administrator","member","supervisor"

View

          @foreach (var list in ViewBag.role)
            {
            <input type="checkbox" name="role" [email protected] /> @list.Name
            }

How Can I loop through the ViewBag.allrole array string in jquery and checked the checked box which have value that is in the ViewBag.allrole array string. Edited In View It Creates Entire set of Checkbox of all avaiable Role as follows:

<input type="checkbox" value="Administrator" name="role">
Administrator
<input type="checkbox" value="Moderator" name="role">
Moderator
<input type="checkbox" value="voice" name="role">
voiceanchor
<input type="checkbox" value="member" name="role">
member 

If the ViewBag.allrole consist of array of "administrator","moderator" then I want to checked the checkbox with those value in checkbox using jquery

3
  • 1
    Where are the roles that are not checked coming from? Commented Dec 11, 2012 at 10:15
  • if the role is not in ViewBag.allrole is not checked. Commented Dec 11, 2012 at 10:20
  • Ok, let me put it another way, where is the code that creates the checkboxes for the entire set of roles? Commented Dec 11, 2012 at 10:33

1 Answer 1

1

If you are using .NET Membership, you can do something like:

@foreach (var role in Roles.GetAllRoles)
{
    bool checked = Roles.IsUserInRole(role);

    <input 
         type="checkbox"  
         name="role" 
         value="@role.Name" 
         @(checked ? "checked='checked'" : "")/> @role.Name
}

in your particular example, you can do almost the same

string[] userRoles = ViewBag.role;

@foreach (var list in ViewBag.allrole)
{
    bool checked = userRoles.Contains(role);

    <input 
         type="checkbox" 
         name="role" 
         value="@list.Name" 
         @(checked ? "checked='checked'" : "")/> @list.Name
}

please change your variables accordingly if I missed something, as they're not very intuitive.

Sign up to request clarification or add additional context in comments.

1 Comment

The second one actually worked. I was so confused as two viewbags created a mess. saved me thanks!. .Contains() did a top notch work!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.