3

我是MVC3的新手,一直在使用EF和'Code First'工作。我试图在处理下拉列表的视图中做一些事情,并且想知道最好的方法是什么。我希望用户能够从下拉列表中选择规则,并根据选择的规则,我希望页面上的标签显示规则名称(不发布)。我还需要能够将选定的规则发送到下一页。我还没有将所有必要的字段添加到视图中,因为我对它的工作方式感到不知所措。我应该如何去做这件事?了解DropDownListFor如何在MVC3中工作

我有我的模型:

public class D1K2N3CARule 
{ 
    public int ID { get; set; } 
    [Required] 
    public int Name { get; set; } 
    [Required] 
    public string Rule { get; set; } 

    public D1K2N3CARule(int name, string rule) 
    { 
     Name = name; 
     Rule = rule; 
    } 
    public D1K2N3CARule() 
    { 
     Name = 0; 
     Rule = ""; 
    } 
} 

我的视图模型:

public class D1K2N3CARuleViewModel 
{ 
    public string SelectedD1K2N3CARuleId { get; set; } 
    public IEnumerable<D1K2N3CARule> D1K2N3CARules { get; set; } 
} 

我的控制器:

public ActionResult Index() 
    { 
     var model = new D1K2N3CARuleViewModel 
     { 
      D1K2N3CARules = db.D1K2N3DARules 
     }; 

     return View(model); 
    } 

,我的观点:

'@model CellularAutomata.Models.D1K2N3CARuleViewModel 

@{ 
    ViewBag.Title = "Index"; 
} 
<asp:Content id="head" contentplaceholderid="head" runat="server"> 
<script type="text/javascript"> 
</script> 
</asp:Content> 
<h2>Index</h2> 

<table> 
    <tr> 
     <td> 
      @Html.DropDownListFor(
       x => x.D1K2N3CARules, 
       new SelectList(Model.D1K2N3CARules, "ID","Rule") 
      ) 
     </td> 
    </tr> 
</table>' 

回答

4

我希望用户能够选择从下拉列表的规则,并根据该规则被选中,我想在网页上的标签,以显示规则名称(不含发布)

你需要在这里使用javascript。 jQuery将是完美的工作。我会通过下拉提供确定性的ID开始,因为如果你运行一个模板内这种观点可能有前缀加入到这会毁了我们的JavaScript的ID选择(见下文)ID:

@Html.DropDownListFor(
    x => x.D1K2N3CARules, 
    new SelectList(Model.D1K2N3CARules, "ID", "Rule"), 
    new { id = "ruleDdl" } 
) 

然后提供一些容器,其将接收所选择的值:

<div id="ruleValue" /> 

,最后在一个单独的JavaScript文件认购下拉列表的变化事件,并更新与所选择的值/文本容器:

$(function() { 
    // subscribe for the change event of the dropdown 
    $('#ruleDdl').change(function() { 
     // get the selected text from the dropdown 
     var selectedText = $(this).find('option:selected').text(); 

     // if you wanted the selected value you could: 
     // var selectedValue = $(this).val(); 

     // show the value inside the container 
     $('#ruleValue').html(selectedText); 
    }); 
}); 

我还需要能够将选定的规则发送到下一页。

你可以把你的下拉表单

@using (Html.BeginForm("NextPage", "Foo")) 
{ 
    @Html.DropDownListFor(
     x => x.D1K2N3CARules, 
     new SelectList(Model.D1K2N3CARules, "ID","Rule") 
    )  
    <input type="submit" value="Go to the next page" /> 
} 

和下一页控制器动作内将获得选择的值。

+0

什么参数传递回下一页控制器?我所尝试的每件事都会通过null结束。我四处寻找答案的最后几个小时,然后继续空着。你有没有关于MVC3的好资源的建议?我明显在旋转我的轮子,我想我需要做一些阅读。 – 2011-02-24 15:20:59

+1

@Doug S.只有你在表单中包含的内容才会被传递给下一个控制器。在这个例子中,我们只有一个下拉列表,因此只有选定的值会被发送。 – 2011-02-24 15:39:54

+0

我明白,但我在我的下一页控制器中指定了什么参数? 公众的ActionResult RunCA(字符串ID) 或 公众的ActionResult RunCA(selectlistitem项目) 或 公众的ActionResult RunCA(INT ID) 一切我已经试过了复出空。 – 2011-02-24 15:50:24