Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Alex 18 posts 90 karma points
    Apr 16, 2022 @ 20:06
    Alex
    0

    Getting the value from a DropDownList on my controller

    Hello,

    This is supposed to be easy but didn't manage to find it:

    On my partial Form I can get all the string values but can't get the selected value from this one:

      @Html.DropDownListFor(x => Model.SList, (IEnumerable<SelectListItem>)MyList)
    

    which is being populated simply from this:

     List<SelectListItem> MyList = new List<SelectListItem>();
        MyList.Add(new SelectListItem() { Text = "Text 1", Value = "Value 1" });
        MyList.Add(new SelectListItem() { Text = "Text 2", Value = "Value 2" });
    

    On my controller which inherits from the SurfaceController I have :

    public class WebFormModel
        {
        public List<SelectListItem> SList { get; set; }
    
    }
    

    But when I get the value from here:

    private void SendSmtpEmail(....
    body.AppendLine(model.SList);
     )
    

    It returns: System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]

    Some help so I can get the selected value or text ("Text 1" or "Value 1") will be appreciated.

    Thank you.

  • Paul Seal 524 posts 2889 karma points MVP 7x c-trib
    Apr 18, 2022 @ 10:07
    Paul Seal
    100

    Hi

    The property SList should be a string. All it is going to do is store the value of the selected item.

    I normally have the property as a string and I load the options into another property as an IEnumerable

    Here is an example view model (on my phone)

    using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc;

    namespace CodeShare.Core.Models.ViewModels { public class EditProfileViewModel { [Display(Name = "Job Title")] public string JobTitle { get; set; }

        public IEnumerable<SelectListItem> JobTitleOptions { get; set; }
    }
    

    }

    Then when I do the dropdown on the page I call it like this:

    @Html.DropDownListFor(x => x.JobTitle, Model.JobTitleOptions, "Please select..")

    I hope that helps.

    Paul

  • Alex 18 posts 90 karma points
    Apr 18, 2022 @ 10:54
    Alex
    0

    Thank you Paul, that was so simple!

    PS: Your Umbraco youtube videos have been so helpful, thanks again!

  • Paul Seal 524 posts 2889 karma points MVP 7x c-trib
    Apr 18, 2022 @ 13:50
    Paul Seal
    0

    You’re welcome mate.

    I’m so glad you like the videos. I’ll be doing a v9 series soon.

  • Alex 18 posts 90 karma points
    Apr 18, 2022 @ 15:22
    Alex
    0

    Umbraco 9 videos, it sounds great

Please Sign in or register to post replies

Write your reply to:

Draft