简体   繁体   English

ASP.NET MVC中的DropdownList-未发布值

[英]DropdownList in ASP.NET MVC - value not posted

I have a form in ASP MVC (Razor) and in this form I have a Textboxes... and a <select> and I want to transmit the selected option (value) of this select to the controller like the other information. 我在ASP MVC(Razor)中有一个表单,在此表单中,我有一个Textboxes ...和<select> ,我想像其他信息一样将此选择的选定选项(值)传输到控制器。 The textboxes are transmitted correctly to the controller and it's in the database. 文本框已正确传输到控制器,并且在数据库中。

I have a field in the database called NumberParticipant and I want to transmit i tin the database thanks to my Create controller : 我在数据库中有一个名为NumberParticipant的字段,由于我的Create控制器,我想传输该数据库:

My code : 我的代码:

@using (Html.BeginForm())
{
  <div class="form-group">
    @Html.LabelFor(model => model.LocalNumber, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
      @Html.EditorFor(model => model.LocalNumber, new { htmlAttributes = new { @class = "form-control" } })
      @Html.ValidationMessageFor(model => model.LocalNumber)
    </div>
  </div>
  <div class="col-md-10">
    <select class="form-control" id="numberParticipant">
      <option value=""></option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
    </select>
  </div>
  <input type="submit" value="Create" class="btn btn-default" />
}

Using the MVC DropDownList helper would save you from writing out all the html. 使用MVC DropDownList帮助器可以避免编写所有html。 Here's an example that sets the option values in the view. 这是一个在视图中设置选项值的示例。

<div class="col-md-10">
    @Html.DropDownListFor(model => model.NumberParticipant, 
        new SelectList(new [] 
        { new {value="",text=""},
          new {value="2",text="2"},
          new {value="3",text="3"},
          new {value="4",text="4"},
          new {value="5",text="5"}
    },"value","text"), new { htmlAttributes = new { @class = "form-control" }})
</div>

A best practice would be to add a property of type SelectList to your model class and set the possible options there. 最佳实践是在模型类中添加SelectList类型的属性,并在那里设置可能的选项。 You could then reference the new property in the helper like this: 然后,您可以像这样在助手中引用新属性:

<div class="col-md-10">
    @Html.DropDownListFor(model => model.NumberParticipant, 
        Model.MySelectList, new { htmlAttributes = new { @class = "form-control" }})
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM