MVC5 Razor html.dropdownlistfor set selected when value is in array

后端 未结 3 743
旧巷少年郎
旧巷少年郎 2020-11-22 00:56

I\'m developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.

I have this View:

@model MyProject.Web.API.Models.Aggreg         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 01:29

    I wrote this class to overcome an issue I was having with selecting an option in an html select list. I hope it helps someone.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    
    namespace Login_page.Models
    {
        public class HTMLSelect
        {
            public string id { get; set; }
            public IEnumerable @class { get; set; }
            public string name { get; set; }
            public Boolean required { get; set; }
            public string size { get; set; }
            public IEnumerable SelectOptions { get; set; }
    
            public HTMLSelect(IEnumerable options)
            {
    
            }
    
            public HTMLSelect(string id, string name)
            {
                this.id = id;
                this.name = name;
            }
    
            public HTMLSelect(string id, string name, bool required, IEnumerable options)
            {
                this.id = id;
                this.name = name;
                this.required = required;
            }
    
            private string BuildOpeningTag()
            {
                StringBuilder text = new StringBuilder();
                text.Append("");
                return text.ToString();
    
            }
    
            public string GenerateSelect(IEnumerable options)
            {
                StringBuilder selectElement = new StringBuilder();
                selectElement.Append(this.BuildOpeningTag());
                foreach (SelectOption option in options)
                {
                    StringBuilder text = new StringBuilder();
                    text.Append("\t");
                    text.Append("");
                    selectElement.Append(text.ToString());
                }
                selectElement.Append("

    And

    public IEnumerable getOrderTypes()
    {
        List orderTypes = new List();
                            if (this.orderType == "OptionText")
                            {
                                orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
                            } else
                            {
                                orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
                            }
    }
    

    And to use it:

    @{
        Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
    
    }
    @Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
    

提交回复
热议问题