Hubert Solecki
Hubert Solecki

Reputation: 2761

how to add object to a list in a view?

I have a strongly typed view where I have a form. I display values of a Contact (object) in Textboxes. The contact has a list of functions. I have also a list of all the functions that exist in database. In the view I'm listing all the functions by displaying checkboxes (value : Id of the function, display : name of the function). Before that, I compare the list of the Contact's functions to all to functions and I checked those of the contact. Like that :

 @foreach (extranetClient.Models.Classes.FonctionContact fonction in ViewBag.Fonctions)
         {
                string coche = "";
                if ((@Model.ListeFonctions).Where(c => c.IdFonction == fonction.IdFonction).Count() > 0)
                     {
                          coche = "checked";
                     }

                <input type="checkbox" @coche id="@fonction.IdFonction" />@fonction.LibelleFonction <br />
         }

It looks like that:

enter image description here

But now, if the user checks a checkbox to add a function to the contact, I need to save it in the contact's list. I cannot find how to do that. Somebody has idea ?

Upvotes: 1

Views: 48

Answers (1)

Jay
Jay

Reputation: 6294

First we need to modify your checkboxes so they will post properly. When a checkbox is checked it will be posted like this name=value. But we want all your checkboxes to be posted into a collection, so the name will follow this format function[x] where x is an index of the checkbox. The value then becomes the ID of the function.

@{
    var i = 0;
}
@foreach (extranetClient.Models.Classes.FonctionContact fonction in ViewBag.Fonctions)
{
    string coche = "";
    if ((@Model.ListeFonctions).Any(c => c.IdFonction == fonction.IdFonction))
    {
        coche = "checked";
    }

    <input type="checkbox" @coche id="functions[@(i++)]" value="@fonction.IdFonction" />@fonction.LibelleFonction <br />
}

Now create an action method which can receive the checkboxes's data. Simply provide a parameter which can recieve an enumeration of int assuming your function IDs are ints.

public ActionResult UpdateFunctions(IEnumerable<int> functions)
{
    // TODO: functions contains IDs of all checked boxes.
}

Hope this helps.

Upvotes: 1

Related Questions