我在视图中有下拉列表如下:
<td>
@Html.DropDownListFor(model => model.Priority, new SelectList(new List<object>{
new { value="Select", text= "--Select--" },
new { value="High", text= "High" },
new { value ="Normal", text= "Normal" },
new { value ="Low", text= "Low" }
}, "value", "text", 0), new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Priority, "", new { @class = "text-danger" })
</td>
我在DB中将'Priority'字段的值设置为'Normal','Low','High'。我想绑定选定的值以在编辑视图中绑定。我将数据传递给编辑视图,如下所示:
public ActionResult EditTaskDetails(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
List<Task_Detail> Tasks = new List<Task_Detail>();
Task_Detail TaskDet = new Task_Detail();
Tasks = new TaskDAO().GetTaskDetailById(id);
ViewData["TaskDetails"] = Tasks;
return View();
}
在View中,我绑定其他数据如下:
@foreach (var task in ViewBag.TaskDetails)
{
<table>
<tr>
<td>
@Html.TextBoxFor(model => model.Task_Code, new { id = "txtTCode", Value = @task.Task_Code, @class = "form-control" })
@Html.ValidationMessageFor(model => model.Task_Code, "", new { @class = "text-danger" })
</td>
</tr>
</table>
现在,如何将此选定状态值绑定到控制器的下拉列表中? 任何人都可以帮我这样做.. 提前谢谢..
答案 0 :(得分:0)
使用这些值创建枚举:
public enum ValPriorities
{
High = 1,
Normal = 2,
Low = 3
}
然后创建一个选择列表对象:
var selectList= new SelectList(Enum.GetValues(typeof(ValPriorities)).Cast<ValPriorities>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
}).ToList(),"Value","Text");
然后在你的控制器中:
ViewData["selectList"] = selectList;
或者您可以将其创建为模型属性并将其发送为:
return View(yourModel);
在你看来:
@Html.DropDownListFor(model => model.ID, ViewData["selectList"],"--Select--", new { @class = "form-control" })