【问题标题】:asp.net grab selected form valueasp.net 抓取选定的表单值
【发布时间】:2016-12-25 18:35:25
【问题描述】:

如何从控制器的视图上的下拉列表中获取所选值?

型号:

public class CustomerInformation
{
    public Dictionary<int, string> State { get; set; }
    public CustomerInformation()
    {
        State = new Dictionary<int, string>()
        {
            { 0, "California"},
            { 1, "Nevada"}
        };
    }
}

控制器

public ActionResult Index()
{
    var model = new CustomerInformation.Models.CustomerInformation();
    return View(model);
}

public ActionResult ShowData(CustomerInformation.Models.CustomerInformation _customerInformation)
{
   //..
}

查看

@using (Html.BeginForm("ShowData", "Home"))
{
    @Html.Label("State:: ");
    @Html.DropDownListFor(m => m.State, new SelectList(Model.State, "Key", "Value"))   
    <input type="submit" value="Submit" />
}

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    您的模型需要StateId 属性。然后你可以在你的发布值中得到它......

    public class CustomerInformation
    {
        public Dictionary<int, string> State { get; set; }
     public int StateId {get;set;}   
     public CustomerInformation()
        {
            State = new Dictionary<int, string>()
            {
                { 0, "California"},
                { 1, "Nevada"}
            };
        }
    }
    

    这是您要更改 html 选择列表的 id 和名称的地方:

    @Html.DropDownListFor(m => m.StateId, new SelectList(Model.State, "Key", "Value"))   
    

    然后在你的 Post 方法中:

    public ActionResult ShowData(CustomerInformation.Models.CustomerInformation _customerInformation)
    {
       _customerInformation.StateId // The selected value.
    } 
    

    【讨论】:

      【解决方案2】:

      我需要添加到我的模型中

      public int id { get; set; }
      

      保存推算的选定下拉值

      然后在我看来分配那个值

      @Html.DropDownListFor(m => m.id, new SelectList(Model.State, "Key", "Value"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-09
        • 2013-06-05
        • 2017-03-23
        • 1970-01-01
        • 1970-01-01
        • 2014-05-14
        相关资源
        最近更新 更多