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