无法将DropDownListFor中的数据插入数据库

时间:2017-09-26 12:54:32

标签: c# asp.net-mvc

我使用Dictionary将数据填充到DropDownListFor中。现在问题是我无法获取DropDownListFor的onchange事件的密钥。 我想要的是代表select客户端的KEY选择Schema。

控制器:=

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; }
}

观看=&gt;

<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>

1 个答案:

答案 0 :(得分: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>
}