locked
display string message for integer type attributes RRS feed

  • Question

  • User364607740 posted

    I have a model class,

    namespace myapp.Models
    {
        public class SchoolModels
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
            [Required]
            public int ShoolType { get; set; }        
        }
    }

    In Create.cshtml page, I have created a static drop down list to select the value for ShoolType attribute.

    @Html.DropDownList("ShoolType", new List<SelectListItem>
    	{
    		new SelectListItem {Text = "community", Value = "1"},
    		new SelectListItem {Text = "boarding", Value = "2"},
    		new SelectListItem {Text = "others", Value = "3"}
    	}, "select shool type")

    But in Index.cshtml page, I am getting the integer values for ShoolType. How can I display the ShoolType as community for 1, boarding for 2 and others for 3?

    public ActionResult Index()
            {
                return View(db.Schools.ToList());
            }

    Friday, July 31, 2020 5:45 AM

All replies

  • User753101303 posted

    Hi,

    You could consider to have a SchoolType entity with an id and a name. This way you'll be able to both know the type name for a given value but you'll be also able to add another school type at any time without any code change.

    Another option is to use an enum: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum

    Friday, July 31, 2020 10:16 AM
  • User-2121988648 posted

    scala_1988

    { new SelectListItem {Text = "community", Value = "1"}, new SelectListItem {Text = "boarding", Value = "2"}, new SelectListItem {Text = "others", Value = "3"} }, "select shool type")

    @Html.DropDownList("ShoolType", new List<SelectListItem>
    	{
    		new SelectListItem {Text = "community", Value = "community"},
    		new SelectListItem {Text = "boarding", Value = "boarding"},
    		new SelectListItem {Text = "others", Value = "others"}
    	}, "select shool type")

    Try this and change to string. Also, you can create enum to solve this issue 

    Friday, July 31, 2020 11:16 AM
  • User-2121988648 posted
      public enum ShoolType
      {
            Community=1,
            Boarding=2,
            Others=3
       }
    namespace myapp.Models
    {
        public class SchoolModels
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
            [Required]
            public ShoolType ShoolType { get; set; }        
        }
    }
    @Html.DropDownList("ShoolType", 
    new SelectList(Enum.GetValues(typeof(TestSolution1.UI.Data.ShoolType))), "select shool type")

    Friday, July 31, 2020 11:24 AM