【问题标题】:Hard coding two items in a list硬编码列表中的两个项目
【发布时间】:2016-05-10 03:00:16
【问题描述】:

这是我的剃须刀:

@Html.DropDownListFor(m => m.CountryCode,  ???? , new { @class = "form-control styled-select", id = "CountryCode", name = "CountryCode" })

如何在 ???? 参数中创建“美国”和“加拿大”的选定列表项?我无法正确使用语法。

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    向您的视图模型添加一个新属性以存储国家/地区列表。该属性的类型可以是SelectListItem的集合。

    public class CreateSomething
    {
       public List<SelectListItem> Countries { set;get;}
       //Your existing properties
       public string CountryCode { set;get; }
    }
    

    在您的 GET 操作中,只需使用一些数据加载此属性。

    public ActionResult Create()
    {
       var vm= new CreateSomething();
       vm.Countries= new List<SelectListItem> {
                                            new SelectListItem { Value="USA", Text="USA"},
                                            new SelectListItem { Value="CANADA", Text="Canada"}
       };
       return View(vm);
    }
    

    在你看来

    @model CreateSomething
    @using(Html.BeginForm())
    {
       <label> Select a country </label>
       @Html.DropDownListFor(m => m.CountryCode,Model.Countries)
       <input type="submit" />
    }
    

    【讨论】:

      【解决方案2】:

      硬编码选项

      如果您真的想要一个硬编码选项,您可以创建一个包含两个目标值的 SelectList

      @Html.DropDownListFor(m => m.CountryCode, new SelectList(new []{ "USA","CANADA" }), ...)
      

      或者只是显式创建一个&lt;select&gt; 元素来为您处理它,老实说,这可能比使用实际的 HTML Helpers 更具可读性:

      <select id='CountryCode' name='CountryCode' class='form-control styled-select'>
          <option>USA</option>
          <option>CANADA</option>
      </select>
      

      否则,使用模型

      如果这些选项看起来不适合您的场景,您应该考虑使用更基于 MVC 的方法,例如创建模型来存储这些属性或将它们存储在像 ViewBag 这样的容器中并将它们传递到你的视图,类似于the approach in Shyju's response

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2022-12-20
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 2015-03-08
        相关资源
        最近更新 更多