2017-09-26 38 views
0

我正在使用Dictionary將數據填充到DropDownListFor中。現在的問題是我無法在DropDownListFor的onchange事件上獲取密鑰。 我想要的是代表選擇客戶端的KEY選擇Schema。無法將數據從DropDownListFor插入數據庫

控制器:=

public ActionResult Index() 
{ 
    DataComponents dcomponents = new Models.DataComponents(); 
    //Getting Data From Database to Dictionary 
    dcomponents.clientName = getdata.Clients(); 
    dcomponents.schemaName = getdata.Schemas(); 
    return View(dcomponents); 
} 
public ActionResult Change(DataComponents dcomponents) 
{ 
    //Select data on behalf of Client ID 
    dcomponents.clientName = getdata.Clients(); 
    dcomponents.schemaName = getdata.Schemas(dcomponents.selectedClient);    
    return View("Index",dcomponents); 
} 

型號=>

public class DataComponents 
{ 
    public Dictionary<int,string> clientName { get; set; } 
    public int selectedClient { get; set; } 
    public Dictionary<int, string> schemaName { get; set; } 
    public int selectedSchema { get; set; } 
} 

查看=>

<td> 
@Html.DropDownListFor(m => m.selectedClient,new SelectList(Model.clientName,"key","Value",Model.selectedClient), "Select Client", new { onchange = "document.location.href = '/Home/Change';" }) 
</td> 
<td> 
    @Html.DropDownListFor(m => m.selectedSchema, new SelectList(Model.schemaName, "key", "Value", Model.selectedClient), "Select Schema", new { onchange = "document.location.href = '/Home/Change';" })) 
</td> 
+0

您的小寫鍵在您的視圖中可能是您​​唯一的問題。要選擇字典的示例:new SelectList(dict.OrderBy(x => x.Value),「Key」,「Value」,selectedValue); –

+0

仍然無法工作。 –

+0

我不知道你的變化是否會起作用。您未提交表單或將任何類型的內容發送給重定向。你只是做一個GET/Home/Change。 嘗試在表單中包裹drowpdowns並使用onchange提交表單 –

回答

0

您需要將數據獲取到服務器。無論是通過帖子,還是通過查詢字符串。我將事物建模爲一個帖子。

您可以看到我在窗體中包裝了視圖信息,並更改了事件以便在更改時提交窗體。

public ActionResult Index() 
{ 
    DataComponents dcomponents = new Models.DataComponents(); 
    //Getting Data From Database to Dictionary 
    dcomponents.clientName = getdata.Clients(); 
    dcomponents.schemaName = getdata.Schemas(); 
    return View(dcomponents); 
} 
[HttpPost] 
public ActionResult Change(DataComponents dcomponents) 
{ 
    //Select data on behalf of Client ID 
    dcomponents.clientName = getdata.Clients(); 
    dcomponents.schemaName = getdata.Schemas(dcomponents.selectedClient);    
    return View("Index",dcomponents); 
} 

@using (Html.BeginForm("Change", "Home", FormMethod.Post)) 
{ 
    <td> 
     @Html.DropDownListFor(m => m.selectedClient,new SelectList(Model.clientName,"key","Value",Model.selectedClient), "Select Client", new { "this.form.submit();" }) 
    </td> 
    <td> 
     @Html.DropDownListFor(m => m.selectedSchema, new SelectList(Model.schemaName, "key", "Value", Model.selectedClient), "Select Schema", new { onchange = "this.form.submit();" })) 
    </td> 
} 
+0

感謝Dan的幫助。 –

相關問題