[英]ASP.NET MVC 4 Razor Edit Selected List Item
I am displaying list of my model objects in a Listbox in my view. 我在视图中的列表框中显示模型对象的列表。
When I select a particular item in the Listbox and click edit, I would like to edit that particular Model object. 当我在列表框中选择一个特定的项目并单击“编辑”时,我想编辑该特定的Model对象。
View : 查看:
@Html.ListBox("Employees", (IEnumerable<SelectListItem>)ViewBag.EmployeesList )
@Html.ActionLink("Edit", "Edit", new { id=????})
I need to get the list box selected item id at runtime to provide it in the actionlink. 我需要在运行时获取列表框选定的项目ID,以在操作链接中提供它。
Controller : 控制器:
public ActionResult Index()
{
var Employees= db.Employees;
ViewBag.EmployeesList = new SelectList(Employees, "EmployeeID", "EmployeeName");
return View();
}
public ActionResult Edit(int id)
{
Employee employee = db.Employees.Find(id);
return View();
}
[HttpPost]
public ActionResult Edit(Employee emp)
{
try
{
// TODO: Add update logic here
if (ModelState.IsValid)
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(emp);
}
}
I am not able to get the right URL like: 我无法获得正确的网址,例如:
http://127.0.0.1:81/Employee/Edit/1
The listbox can have multiple selected items so you need to create two lists in a model. 该列表框可以具有多个选定项,因此您需要在模型中创建两个列表。
Something like this: 像这样:
public class EmployeeViewModel
{
public string[] SelectedEmployeesList { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
The first for the selected items and the second for the items in the list. 第一个用于所选项目,第二个用于列表中的项目。
In your Edit get method you need to set the model list items and return it to the view ie 在您的Edit get方法中,您需要设置模型列表项并将其返回到视图,即
public ActionResult Edit(int id)
{
var model = new EmployeeViewModel();
Employee employee = db.Employees.Find(id);
var model = new EmployeeViewModel
{
Items = new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "Employee 1" },
new SelectListItem { Value = "2", Text = "Employee 2" },
}, "Value", "Text")
};
model.SelectedEmployeeList = new [] {1};
return View(model);
}
In your view it will be something like this: 您认为它将是这样的:
Html.ListBoxFor(model => model.SelectedEmployeeList, Model.Items)
Sorry I have not had time to check this code for errors, hope it works for you. 抱歉,我没有时间检查此代码中的错误,希望它对您有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.