2012-12-14 43 views
5

我有一个html选择器,我想在我的表单中为我的“model => model.type”使用选定的值。有没有办法将我的@Html.EditorFor(model => model.type)中的值设置为选择器的值?在剃刀上使用html选择框

@using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 
<fieldset> 
    <legend>Bet</legend> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.type) 
    </div> 
    <div class="editor-field"> 

     <select id ="type"> 
    <option value="Football">Football</option> 
    <option value="Rugby">Rugby</option> 
    <option value="Horse Racing">Horse Racing</option> 
</select> 

     @Html.EditorFor(model => model.type) 
     @Html.ValidationMessageFor(model => model.type) 

    </div> 



    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 
+0

你不能用剃刀做到这一点,你必须使用Javascript,你可以使用jQuery吗? –

+1

为什么你需要两个类型属性的控件?你有什么具体的理由不使用一个下拉列表? –

+0

对不起,我的错误,我明白你想在“输入”中输入“select”的值 –

回答

16

您可以使用此选项尝试:

型号:

public string Type { get; set; } 

public IEnumerable<SelectListItem> TypeList 
{ 
    get 
    { 
     return new List<SelectListItem> 
     { 
      new SelectListItem { Text = "Football", Value = "Football"}, 
      new SelectListItem { Text = "Rugby", Value = "Rugby"}, 
      new SelectListItem { Text = "Horse Racing", Value = "Horse Racing"} 
     }; 
    } 
} 

HTML(剃刀):

@Html.DropDownListFor(model => model.Type, Model.TypeList) 

OR

HTML(剃刀):

当我们从控制器模型传递给视图
@Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, Model.Type)) 
+0

我得到:System.NullReferenceException:未将对象引用设置为对象的实例。 – Nick

+1

我只想强调有两个名为'SelectListItem'的类,你想要的是'System.Web.Mvc',而**不是'System.Web.WebPages.Html'中的那个。 – Jocie

+0

Hi @NickG,你是否继续这个问题?也许你可以创建一个问题,然后你可以在这里复制链接 –

1

由@andresdescalzo提供的解决方案仅适用。

public class SomeController : Controller 
{ 
    public ActionResult SomeAction() 
    { 
    return View(new SomeModelWithIEnumerationsSelectListItem()) 
    } 
} 
0

的除了现有的答案:如果你得到的异常实现@ andresdescalzo的解决方案时,“未设置为一个对象的实例对象引用”,你要么需要:

  1. 退运模型,你正在使用@diwas提到
  2. 在剃须刀页面上实例化一个模型,以便您可以调用该方法。如果您使用ViewModel而不是简单的EF模型,这很有用。

第二个可以做这样的:

@{ var tempModel = new YourNameSpace.Models.YourModel(); } 
@Html.DropDownListFor(model => model.Type, tempModel.TypeList, Model.Type)) 
0

@ andresdescalzo的解决方案(最后一个)的作品有一个小的改动:

@Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, "Rugby"), htmlAttributes: new { @class = "form-control" }) 


第一:添加用于下拉列表的选定项目(例如“橄榄球”)
二:除去最后Model.Type并添加htmlAttributes

PS:列表SelectedList开括号关闭选定后项目(这里是“Rugby”)