2017-09-26 82 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的帮助。 –

相关问题