Asp.net mvc 3 如何将DropDownList中的选择分配给MVC3中的数据模型
我正在从服务中检索一些配置,并将这些数据传递到编辑视图。用户可以对文本和复选框字段进行更改,并且这些值可以很好地返回 我有一个下拉列表,其中填充了数据库类型枚举中的值。这些值将传递到视图并正确显示,但当用户更改选择时,列表中的第一个值将应用于数据模型 下面是控制器和视图中的一些代码 控制员:Asp.net mvc 3 如何将DropDownList中的选择分配给MVC3中的数据模型,asp.net-mvc-3,Asp.net Mvc 3,我正在从服务中检索一些配置,并将这些数据传递到编辑视图。用户可以对文本和复选框字段进行更改,并且这些值可以很好地返回 我有一个下拉列表,其中填充了数据库类型枚举中的值。这些值将传递到视图并正确显示,但当用户更改选择时,列表中的第一个值将应用于数据模型 下面是控制器和视图中的一些代码 控制员: [HttpPost] public ActionResult Edit( SettingsModel config) { try { List<string> c
[HttpPost]
public ActionResult Edit( SettingsModel config)
{
try
{
List<string> configErrors = null;
if (ModelState.IsValid)
{
// Set up a channel factory to use the webHTTPBinding
using (WebChannelFactory<IChangeService> serviceChannel = new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl)))
{
IChangeService channel = serviceChannel.CreateChannel();
configErrors = channel.SetSysConfig(config);
// Check for any errors returned by the service
if (configErrors != null || configErrors.Count > 0)
{
// Display the errors at the top of the page
ViewData["ConfigErrors"] = configErrors;
// TODO: Force the redisplay of the page
}
}
}
ViewData["DBTypes"] = new SelectList(Enum.GetValues(typeof(DatabaseType)), config.DBType);
return RedirectToAction("Index", config);
}
catch
{
return View();
}
}
[HttpPost]
公共操作结果编辑(设置模型配置)
{
尝试
{
列表配置错误=null;
if(ModelState.IsValid)
{
//设置通道工厂以使用webHTTPBinding
使用(WebChannel Factory serviceChannel=new WebChannel Factory(新Uri(baseServiceUrl)))
{
IChangeService channel=serviceChannel.CreateChannel();
configErrors=channel.SetSysConfig(配置);
//检查服务返回的任何错误
if(configErrors!=null | | configErrors.Count>0)
{
//在页面顶部显示错误
ViewData[“ConfigErrors”]=ConfigErrors;
//TODO:强制重新显示页面
}
}
}
ViewData[“DBTypes”]=新的选择列表(Enum.GetValues(typeof(DatabaseType)),config.DBType);
返回重定向操作(“索引”,配置);
}
接住
{
返回视图();
}
}
编辑视图:
<tr>
<td>
<h4>Database Type</h4>
</td>
<td>
@Html.DropDownList("Database Type", ViewData["DBTypes"] as SelectList )
</td>
<td>
@Html.ValidationMessageFor(model => model.DBType)
</td>
</tr>
数据库类型
@Html.DropDownList(“数据库类型”,ViewData[“DBTypes”]作为SelectList)
@Html.ValidationMessageFor(model=>model.DBType)
尝试像这样更改视图
@Html.DropDownListFor(model => model.DBType, ViewData["DBTypes"] as SelectList, "select a value")
这应该将选择保留到模型的属性DBType
或者像这样更改行以获得相同的结果
@Html.DropDownList("DBType", ViewData["DBTypes"] as SelectList )