Search code examples
c#asp.net-mvc-4html.listboxfor

getting the sum of the selected values in a listbox in c# MVC4


i'm trying to create a multiselect listbox and display the sum of its SELECTED items. So here what I did: I created a ViewModel

public class profilViewModel
{
  public IEnumerable<SelectListItem> roles { get; set; }
  public IEnumerable<String> Selectedroles { get; set; }
}

And here is the controller:

public   profilViewModelController : Controller
{
    private Context db = new Context();
    //
    // GET: /profilViewModel/
    [HttpGet]
    public ActionResult Index()
    {
        List<SelectListItem> listSelectListItem = new List<SelectListItem();
        foreach (role role in db.role)
        {
            SelectListItem selectListItem = new SelectListItem()
            {
                Text = role.role_name,
                Value = role.role_value.ToString(),
                Selected = role.IsSelected
            };
            listSelectListItem.Add(selectListItem);
        }

        profilViewModel profilViewModel = new profilViewModel();
        profilViewModel.roles = listSelectListItem;
        return View(profilViewModel);
    }

and here is my model:

 public class role
  {
    [Key]
    public int role_id { get; set; }
    public string role_name { get; set; }
    public int role_value { get; set; }
    public Boolean IsSelected { get; set; }
   }

The list box works fine, The problem is that i want to display the sum of the selected items, i tried this method:

public int Index(IEnumerable<int> Selectedroles)
    {
        if (Selectedroles == null)
        { return 0; }
        else
        {
            int result = 0;
           for (int i = 0; i < Selectedroles.Count(); i++)
      {

            result += Convert.ToInt32(Selectedroles);
            return result;
        }

      }

but the convertion doesnt work, am i missin something? thx for your help!

PS: i got inspired from hidden's answer here for my listbox JQuery Get values from Multi Select List if statement MVC3


Solution

  • Should your code look like this

      public int Index(IEnumerable<int> Selectedroles)
      {
        if (Selectedroles == null)
           { return 0; }
        else
        {
          var arr = Selectedroles.ToArray();
            int result = 0;
           for (int i = 0; i < arr.Length; i++)
            {
                result += Convert.ToInt32(arr[i]);
            }
       // another way
          foreach(var r in Selectedroles)
                      result += r;
         return result;
    
      }