C# 为什么multiselect.net mvc不显示选定的值?
我不明白为什么asp mvc 4中的ListBox帮助程序没有显示所选的值。我一直在谷歌上搜索,似乎没有任何东西能解决这个问题。假设我有这样一个控制器:C# 为什么multiselect.net mvc不显示选定的值?,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我不明白为什么asp mvc 4中的ListBox帮助程序没有显示所选的值。我一直在谷歌上搜索,似乎没有任何东西能解决这个问题。假设我有这样一个控制器: public ActionResult CreateDetailsMateria(int IdMateriaCurso) { try { MateriasModel model = new Metodos.Entidades().getMateriaById(IdMateriaCu
public ActionResult CreateDetailsMateria(int IdMateriaCurso)
{
try
{
MateriasModel model = new Metodos.Entidades().getMateriaById(IdMateriaCurso);
model.listaMaterias = new Metodos.Entidades().getAllMaterias();
int materiasNombres = model.IdMateriasNombres;
List<SelectListItem> listadoMaterias = new List<SelectListItem>();
listadoMaterias.Add(new SelectListItem { Text = "Elija una materia...", Value = 0.ToString(), Selected = true });
model.listaMaterias.ForEach(t => listadoMaterias.AddRange(from U in model.listaMaterias
where U.IdMateriasNombres.Equals(t.IdMateriasNombres)
select new SelectListItem
{
Value = U.IdMateriasNombres.ToString(),
Text = U.MateriaNombre,
Selected = U.IdMateriasNombres.Equals(materiasNombres)
}));
ViewBag.ListaMaterias = listadoMaterias;
List<DocentesModel> maestros = new List<DocentesModel>();
maestros = new Metodos.Entidades().getDocentes();
List<DocentesModel> maestrosSeleccionados = model.maestros;
List<SelectListItem> listadoMaestros = new List<SelectListItem>();
listadoMaestros.AddRange(from U in maestros
select new SelectListItem
{
Value = U.IdMaestro.ToString(),
Text = U.Nombres + " " + U.ApellidoPaterno + " " + U.ApellidoMaterno,
Selected = maestrosSeleccionados.Select(t => t.IdMaestro.Equals(U.IdMaestro)).First()
});
MultiSelectList catedraticos = new MultiSelectList(listadoMaestros, "Value", "Text", listadoMaestros.Select(a => a.Selected));
ViewBag.ListaMaestros = catedraticos;
ViewBag.datofecha = model.Fecha.Day.ToString();
ViewBag.hora = model.HorarioInicio.Hours.ToString();
return PartialView(model);
}
catch
{
ViewBag.Error = "Ocurrió un error inesperado";
return PartialView();
}
var sampleViewModelList= new List<SampleViewModel>() {
new SampleViewModel() {Id=1, Name="A"},
new SampleViewModel() {Id=2, Name="B"},
new SampleViewModel() {Id=3, Name="C"}
};
ViewBag.SomeList = new SelectList(sampleViewModelList, "Id", "Name",sampleViewModelList.First(x => x.Id == 2).Id);
我不认为这是一个复杂的对象,它只是一个基本体的集合@Stephen Muecke你能澄清一下吗?因为在同一个解决方案中,我可以用一个简单的下拉列表做以下操作:
var allRoles = roles.GetAllRoles().Select(x => new SelectListItem
{
Text = x,
Value = x
}).ToList<SelectListItem>();
allRoles.Add(new SelectListItem { Text = "Escoja...", Value = "", Selected = true });
然后我在我的控制器中:
List<DocentesListasModel> listadoMaestros = new List<DocentesListasModel>();
listadoMaestros.AddRange(from U in maestros
select new DocentesListasModel
{
Id = U.IdMaestro,
Name = U.Nombres+ " "+ U.ApellidoPaterno + " "+U.ApellidoMaterno
});
List<DocentesModel> seleccionadosMasters = maestrosSeleccionados.Where(p => listadoMaestros.Any(t => t.Id.Equals(p.IdMaestro))).ToList();
MultiSelectList catedraticos = new MultiSelectList(listadoMaestros, "Id", "Name", listadoMaestros.Where(t=> seleccionadosMasters.Any(s=> s.IdMaestro.Equals(t.Id))).Select(x => x.Id));
但还是无济于事。它可以正确编译和调试,但与提供的示例相比,它可能过于复杂。问题是我现在无法设计另一个模型,也无法在局部视图中进一步划分,因为我已经在使用局部视图。这个简单的示例可能会帮助您: 视图模型:
public class SampleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
在控制器设置中,如下所示:
public ActionResult CreateDetailsMateria(int IdMateriaCurso)
{
try
{
MateriasModel model = new Metodos.Entidades().getMateriaById(IdMateriaCurso);
model.listaMaterias = new Metodos.Entidades().getAllMaterias();
int materiasNombres = model.IdMateriasNombres;
List<SelectListItem> listadoMaterias = new List<SelectListItem>();
listadoMaterias.Add(new SelectListItem { Text = "Elija una materia...", Value = 0.ToString(), Selected = true });
model.listaMaterias.ForEach(t => listadoMaterias.AddRange(from U in model.listaMaterias
where U.IdMateriasNombres.Equals(t.IdMateriasNombres)
select new SelectListItem
{
Value = U.IdMateriasNombres.ToString(),
Text = U.MateriaNombre,
Selected = U.IdMateriasNombres.Equals(materiasNombres)
}));
ViewBag.ListaMaterias = listadoMaterias;
List<DocentesModel> maestros = new List<DocentesModel>();
maestros = new Metodos.Entidades().getDocentes();
List<DocentesModel> maestrosSeleccionados = model.maestros;
List<SelectListItem> listadoMaestros = new List<SelectListItem>();
listadoMaestros.AddRange(from U in maestros
select new SelectListItem
{
Value = U.IdMaestro.ToString(),
Text = U.Nombres + " " + U.ApellidoPaterno + " " + U.ApellidoMaterno,
Selected = maestrosSeleccionados.Select(t => t.IdMaestro.Equals(U.IdMaestro)).First()
});
MultiSelectList catedraticos = new MultiSelectList(listadoMaestros, "Value", "Text", listadoMaestros.Select(a => a.Selected));
ViewBag.ListaMaestros = catedraticos;
ViewBag.datofecha = model.Fecha.Day.ToString();
ViewBag.hora = model.HorarioInicio.Hours.ToString();
return PartialView(model);
}
catch
{
ViewBag.Error = "Ocurrió un error inesperado";
return PartialView();
}
var sampleViewModelList= new List<SampleViewModel>() {
new SampleViewModel() {Id=1, Name="A"},
new SampleViewModel() {Id=2, Name="B"},
new SampleViewModel() {Id=3, Name="C"}
};
ViewBag.SomeList = new SelectList(sampleViewModelList, "Id", "Name",sampleViewModelList.First(x => x.Id == 2).Id);
首先创建一个视图模型,该模型表示您正在编辑的内容,并删除所有ViewBag内容 视图模型
public class MateriasViewModel
{
public int[] SelectedMaestros { get; set; } // for binding the selected values
public SelectList MaestrosList { get; set; } // for displaying the options
.... // other properties to display/edit in the view
}
控制器
public ActionResult CreateDetailsMateria(int IdMateriaCurso)
{
MateriasViewModel model = new MateriasViewModel();
// Get the data model and map the properties to the view model
....
// Cant understand some of your code so you need to set the values of the following line
model.SelectedMaestros = new int[] { 2, 4 };
// Assign the select list (this is all that's required!)
var listaMaterias = new Metodos.Entidades().getAllMaterias();
model.MaestrosList = new SelectList(listaMaterias, "IdMateriasNombres", "MateriaNombre");
return View(model)
}
看法
如果属性SelectedMaestros的值与属性IDMaterialAsNombRes定义的任何选项值匹配,则在渲染视图时,将在列表框中选择这些选项。例如,如果生成的html是
<select name="SelectedMaestros">
<option value="1">Some text</option>
<option value="2">Some text</option>
<option value="3">Some text</option>
<option value="4">Some text</option>
</select>
SelectedMaestros的值为{2,4},然后将选择第2个和第4个选项什么是mastros?这是你的模型中的一个属性吗?它是IEnumerable吗?它实际上是我的模型中的一个属性,它是另一个类中的一个列表,如行列表maestrosSeleccionados=model.maestros中所示;但是,正如您所看到的,这有点混乱,因为我没有将属性传递给LIstBox,它不是LIstBox,因为我只是将它与ViewBag一起传递。但除此之外,我看不出有什么问题。坦克斯!你犯了很多错误,你可以大大减少你的代码。当您使用@Html.DropDownList绑定到属性时,所选选项将由属性值定义,试图设置SelectListItem的所选属性是无意义的。但maestros似乎是一个复杂对象的集合,所以它在任何情况下都不起作用。属性mastros`必须是int[]类型。好吧,我很困惑。首先,要解决这个问题,您需要一个视图模型。我很快会发布一个答案我需要一些时间来尝试和理解你的代码OK谢谢我会尝试一下,问题是我连接了三个字符串来组成Name属性,但除此之外,它不应该是一个问题。但也许我可以简单地使用IdMaestro属性,它在我的DocentesModelclass中是一个int?我已经用我到目前为止所做的更新了我的问题,但仍然没有显示任何内容,我认为我遵循了您的示例和@111示例的总体思路,尽管我仍然通过ViewBag传递所有内容,因为我不想在已经膨胀的模型中添加属性。当我再次调试时,它会显示正确的值,但标记不会更改。您不应该更改模型。您需要创建一个视图模型。现在只需使用代码n my answer no other属性,就可以看到它是如何工作的。关键问题是1当前为列表,无法将列表框绑定到复杂对象的集合;2如果绑定到的属性被忽略,则无需设置所选属性!。为了帮助您理解模型绑定是如何工作的,请将视图更改为@Html.ListBoxnot-a-property,MultiSelectListmaster-您现在将看到“selected”选项,但这有点毫无意义,因为您发回时它不会绑定,因为没有名为not-a-propertyOMG的此类属性,请不要这样做。创建一个视图模型和do it属性,然后您还可以获得所有其他好处,如验证属性等。一旦您开始正确地进行验证,我假设您将永远不会回头。是的,这是最佳和常见的做法。我建议您也看看这样的工具,它们使您可以轻松地在数据模型和视图模型之间进行映射
public ActionResult CreateDetailsMateria(int IdMateriaCurso)
{
MateriasViewModel model = new MateriasViewModel();
// Get the data model and map the properties to the view model
....
// Cant understand some of your code so you need to set the values of the following line
model.SelectedMaestros = new int[] { 2, 4 };
// Assign the select list (this is all that's required!)
var listaMaterias = new Metodos.Entidades().getAllMaterias();
model.MaestrosList = new SelectList(listaMaterias, "IdMateriasNombres", "MateriaNombre");
return View(model)
}
@model MateriasViewModel
@using(Html.BeginForm())
{
....
@Html.ListBoxFor(m => m.SelectedMaestros, Model.MaestrosList)
....
}
<select name="SelectedMaestros">
<option value="1">Some text</option>
<option value="2">Some text</option>
<option value="3">Some text</option>
<option value="4">Some text</option>
</select>