ASP.NET MVC中的DropdownList-未发布值 [英] DropdownList in ASP.NET MVC - value not posted

查看:46
本文介绍了ASP.NET MVC中的DropdownList-未发布值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP MVC(剃刀)中有一个表单,在此表单中,我有一个Textboxes ...和一个<select>,我想像其他信息一样将此选择的所选选项(值)传输到控制器. .文本框已正确传输到控制器,并且在数据库中.

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. The textboxes are transmitted correctly to the controller and it's in the database.

我在数据库中有一个名为NumberParticipant的字段,由于我的Create控制器,我想传输该数据库:

I have a field in the database called NumberParticipant and I want to transmit i tin the database thanks to my Create controller :

我的代码:

@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" />
}

推荐答案

使用MVC DropDownList帮助器可以避免编写所有html.这是一个在视图中设置选项值的示例.

Using the MVC DropDownList helper would save you from writing out all the 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>

最佳做法是在模型类中添加SelectList类型的属性,并在那里设置可能的选项.然后,您可以像这样在助手中引用新属性:

A best practice would be to add a property of type SelectList to your model class and set the possible options there. 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>

这篇关于ASP.NET MVC中的DropdownList-未发布值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆