How to group by List<object> ViewModel in view - c#

I want to group by vitaminlist, but it's not working.
My Model
public class SearchModel
{
public List<tbbesin> besinlist { get; set; }
public List<tbvitamin> vitaminliste { get; set; }
public List<tbmineral> mineralliste { get; set; }
}
My Controller
public ActionResult ara(BesinViewModel model)
{
var listegetir = model.besinler.Split(',');
List<tbbesin> besinliste = new List<tbbesin>();
List<tbmineral> minerallist = new List<tbmineral>();
List<tbvitamin> vitaminlist = new List<tbvitamin>();
SearchModel modelden = new SearchModel();
foreach (var item in listegetir)
{
var ID = int.Parse(item);
var besin = db.tbbesin.FirstOrDefault(x => x.besinid == ID);
var mineral = db.tbmineral.FirstOrDefault(x => x.besinid == ID);
var vitamin = db.tbvitamin.FirstOrDefault(x => x.besinid == ID);
vitaminlist.Add(vitamin);
minerallist.Add(mineral);
besinliste.Add(besin);
}
modelden.besinlist = besinliste.ToList();
modelden.mineralliste = minerallist.ToList();
modelden.vitaminliste = vitaminlist.ToList();
return View(modelden);
}
My View
#model WebApplication1.Models.SearchModel
#foreach (var item22 in Model.vitaminliste.
GroupBy(x => x.vitamindetayid).
Select(x=>x.First()).
ToList())
{
#item22.tbvitamindetay.vitaminad
}
I need to group by in view vitaminlist but its not working.
Why ? Can you help me what is a problem there

Related

HomeController (String[]) Method is not Valid in Given Context (ASP.Net MVC C#)

I'm currently building a program that processes tickets (agile) in different stages. For some reason I'm having a hard time resolving an error with my home controller and model references. I am being told that model.DueFilter = Filter.DueFilterValue is a method (Filter) which is not valid in the given context.
Below is my Home Controller:
public class HomeController : Controller
{
private TicketContext context;
public HomeController(TicketContext ctx) => context = ctx;
public IActionResult Index(string ID)
{
AgileViewModel model = new AgileViewModel();
var filter = new Filter(ID);
model.Filter = new Filter(ID);
model.Sprints = context.Sprints.ToList();
model.TicketStatuses = context.TicketStatuses.ToList();
model.DueFilter = Filter.DueFilterValue;
IQueryable<Ticket> query = context.Tickets.Include(t => t.Sprint).Include(t => t.TicketStatus);
if (filter.HasSprint)
{
query = query.Where(t => t.SprintID == filter.SprintID);
}
if (filter.HasTicketStatus)
{
query = query.Where(t => t.TicketStatusID == filter.TicketStatusID);
}
if (filter.HasDue)
{
var currentDate = DateTime.Today;
if (filter.isPast)
query = query.Where(t => t.Deadline < currentDate);
else if (filter.isFuture)
query = query.Where(t => t.Deadline > currentDate);
else if (filter.isToday)
query = query.Where(t => t.Deadline == currentDate);
}
var tasks = query.OrderBy(t => t.Deadline).ToList();
model.Tasks = tasks;
return View(model);
}
}
Here is my Filter model:
public class Filter
{
public Filter(string filterstring)
{
FilterString = filterstring ?? "all-all-all";
string[] filter = FilterString.Split('-');
SprintID = filter[0];
Due = filter[1];
TicketStatusID = filter[2];
}
public string FilterString { get; }
public string SprintID { get; }
public string Due { get; }
public string TicketStatusID { get; }
public bool HasSprint => SprintID.ToLower() != "all";
public bool HasDue => Due.ToLower() != "all";
public bool HasTicketStatus => TicketStatusID.ToLower() != "all";
public static Dictionary<string, string> DueFilterValue =>
new Dictionary<string, string>
{
{"future", "Future" },
{"past", "Past" },
{"today", "Today" }
};
public bool isPast => Due.ToLower() == "past";
public bool isFuture => Due.ToLower() == "future";
public bool isToday => Due.ToLower() == "today";
}
Add lastly my ModelView:
public class AgileViewModel
{
public AgileViewModel()
{
CurrentTask = new Ticket();
}
public Filter Filter { get; set; }
public List<TicketStatus> TicketStatuses { get; set; }
public List<Sprint> Sprints { get; set; }
public Dictionary<string, string> DueFilter { get; set; }
public List<Ticket> Tasks { get; set; }
public Ticket CurrentTask { get; set; }
}

Model Binding properties null on asp.net core 3 MVC

could anyone tell me what am I doing wrong? I am getting null properties trying to bind.
Explaining:
My Controller Index looks ok, so that in my View I can see all the input values that I want to bind filled (IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario).
So far, everything looks good. But, after submit the page, in my Controller CheckOut all the properties in checkOut object binded is null, as you can see in the picture.
It was working fine, I dont know what I did so that it now is getting null properties.
I am using asp.net core 3.1 MVC
ViewModel
public class CheckOut
{
public Usuario Usuario { get; set; }
public UsuarioUnidade UsuarioUnidade { get; set; }
public CatalogoEndereco CatalogoEndereco { get; set; }
public UsuarioPagamento UsuarioPagamento { get; set; }
public byte IdPedidoAtendimento { get; set; }
public string PedidoAtendimentoNome { get; set; }
public decimal PedidoAtendimentoTaxa { get; set; }
public DateTime? HorarioAgendado { get; set; }
public byte IdPedidoTipoPagamento { get; set; }
public string PedidoTipoPagamento { get; set; }
public int IdUnidadeUsuario { get; set; }
public string Nome { get; set; }
public string NumEndereco { get; set; }
public string ComplementoEndereco { get; set; }
public string RuaNome { get; set; }
public string CidadeNome { get; set; }
public string EstadoNome { get; set; }
public string CEP { get; set; }
public byte? isCPF { get; set; }
public string CPF { get; set; }
public string NumeroCartao { get; set; }
public string CodCartao { get; set; }
}
Controller
public IActionResult Index()
{
var user = User.FindFirst(ClaimTypes.Name);
if (user != null)
{
Usuario usuario = new Usuario();
usuario = _context.Usuario
.SingleOrDefault(u => u.Email.Equals(user.Value) && u.IsAtivo == true);
CatalogoEndereco catalogoEndereco = new CatalogoEndereco();
catalogoEndereco = _context.CatalogoEndereco
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsAtivo == true && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioPagamento usuarioPagamento = new UsuarioPagamento();
usuarioPagamento = _context.UsuarioPagamento
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioUnidade usuarioUnidade = new UsuarioUnidade();
usuarioUnidade = _context.UsuarioUnidade
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IdUnidadeNavigation.IsAtiva == true && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioAtendimento usuarioAtendimento = new UsuarioAtendimento();
usuarioAtendimento = _context.UsuarioAtendimento
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
.SingleOrDefault();
CheckOut checkOut = new CheckOut()
{
Usuario = usuario,
UsuarioUnidade = usuarioUnidade,
CatalogoEndereco = catalogoEndereco,
UsuarioPagamento = usuarioPagamento,
IdPedidoAtendimento = usuarioAtendimento.Tipo,
PedidoAtendimentoNome = _context.PedidoAtendimento
.FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Nome,
PedidoAtendimentoTaxa = _context.PedidoAtendimento
.FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Taxa
};
if (usuarioAtendimento.Tipo == 1)
{
checkOut.Nome = usuario.Nome;
if (usuarioUnidade != null)
{
checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
}
if (catalogoEndereco != null)
{
checkOut.RuaNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
checkOut.CidadeNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
checkOut.EstadoNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
checkOut.NumEndereco = catalogoEndereco.NumEndereco;
checkOut.ComplementoEndereco = catalogoEndereco.Complemento;
checkOut.CEP = catalogoEndereco.IdEnderecoLogradouroNavigation.Cep;
}
}
else if (usuarioAtendimento.Tipo == 2)
{
if (usuarioUnidade != null)
{
checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
checkOut.Nome = usuarioUnidade.IdUnidadeNavigation.Nome;
checkOut.RuaNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
checkOut.CidadeNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
checkOut.EstadoNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
checkOut.NumEndereco = usuarioUnidade.IdUnidadeNavigation.NumEndereco;
checkOut.CEP = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.Cep;
}
}
if (usuarioPagamento != null)
{
checkOut.IdPedidoTipoPagamento = usuarioPagamento.Tipo;
checkOut.PedidoTipoPagamento = _context.PedidoTipoPagamento
.FirstOrDefault(t => t.IdPedidoTipoPagamento == usuarioPagamento.Tipo).Nome;
checkOut.isCPF = 0;
checkOut.CPF = usuario.Cpf;
checkOut.NumeroCartao = null;
checkOut.CodCartao = null;
if (usuarioPagamento.Tipo == 1 || usuarioPagamento.Tipo == 2)
{
checkOut.NumeroCartao = "**** " + usuarioPagamento.Numero.Substring(12, 4);
checkOut.CodCartao = null;
}
}
return View(checkOut);
}
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CheckOut([Bind("IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario")] CheckOut checkOut)
{
if (ModelState.IsValid)
{
var user = User.FindFirst(ClaimTypes.Name);
if (user != null)
{
var cliente = _context.Usuario.SingleOrDefault(u => u.Email.Equals(user.Value));
var pedido = new Pedido()
{
IdUsuario = cliente.IdUsuario,
IdUnidade = checkOut.IdUnidadeUsuario,
IdPedidoCanalVenda = 1,
IdPedidoAtendimento = checkOut.IdPedidoAtendimento,
IdAtendente = null,
IdPedidoTipoPagamento = checkOut.IdPedidoTipoPagamento,
IdEntregador = null,
IdPedidoStatus = 1,
DataPedido = DateTime.Now,
DataEntrega = null,
HorarioAgendado = null,
TaxaServico = checkOut.PedidoAtendimentoTaxa
};
_context.Pedido.Add(pedido);
await _context.SaveChangesAsync()
.ConfigureAwait(false);
int lastPedido = pedido.IdPedido;
List<Carrinho> cart = JsonSerializeSessionHelper.Get<List<Carrinho>>(HttpContext.Session, "cart");
foreach (var item in cart)
{
var pedidoItens = new PedidoItens
{
IdPedido = lastPedido,
IdProduto = item.IdProduto,
IdProdutoTamanho = item.IdProdutoTamanho,
IdProdutoTipoMassa = item.IdProdutoTipoMassa,
IdProdutoMeia = item.IdProdutoMeia,
Quantidade = item.Quantidade,
Preco = item.Preco
};
_context.PedidoItens.Add(pedidoItens);
}
await _context.SaveChangesAsync()
.ConfigureAwait(false);
TempData["save"] = "Pedido realizado com sucesso";
HttpContext.Session.Remove("cart");
}
else
{
return RedirectToAction("Index", "Login");
}
return RedirectToAction("Index", "Pedido");
}
return View(checkOut);
}
View
#using (Html.BeginForm("CheckOut", "Carrinho", FormMethod.Post))
{
<button type="submit" class="btn btn-info btn-sm">
Pagar (R$ #(#ViewBag.SubTotal + Model.PedidoAtendimentoTaxa))
</button>
// I need these values for Bind!!
#*#Html.DisplayFor(m => m.IdPedidoAtendimento)
#Html.DisplayFor(m => m.PedidoAtendimentoTaxa)
#Html.DisplayFor(m => m.HorarioAgendado)
#Html.DisplayFor(m => m.IdPedidoTipoPagamento)
#Html.DisplayFor(m => m.IdUnidadeUsuario)*#
<input asp-for="IdPedidoAtendimento" value="#Model.IdPedidoAtendimento" id="txtIdPedidoAtendimento" name="txtIdPedidoAtendimento" hidden/>
<input asp-for="PedidoAtendimentoTaxa" value="#Model.PedidoAtendimentoTaxa" id="txtPedidoAtendimentoTaxa" name="txtPedidoAtendimentoTaxa" hidden/>
<input asp-for="HorarioAgendado" value="#Model.HorarioAgendado" id="txtHorarioAgendado" name="txtHorarioAgendado" hidden />
<input asp-for="IdPedidoTipoPagamento" value="#Model.IdPedidoTipoPagamento" id="txtIdPedidoTipoPagamento" name="txtIdPedidoTipoPagamento" hidden/>
<input asp-for="IdUnidadeUsuario" value="#Model.IdUnidadeUsuario" id="txtIdUnidadeUsuario" name="txtIdUnidadeUsuario" hidden/>
}
Model binding occurs based on the name attribute. You have the #Html.DisplayFor lines commented out, so it isn't binding there. For the <input> fields, you have manually entered a name of txt<PropertyName>, so it isn't binding on those, either.
ASP.NET will automatically create an appropriate name attribute just using the asp-for attribute to accommodate model binding.

ASP.NET MVC5 Display data to user with specific selected data"Branch"

I have table with the next columns
Id,Name,A_Status,BranchName.
Would be that expendiently to achive, with the next method, i described bellow?
Column branch has 25 different names. So, i want to create a page, with 25 titles of branch(and for each, create his own cshtml page), where user can enter and view data of that specific branch, he has chosen. On each of those pages specific permissions, not all users can enter and view them.
I decided to achive it with the next code.
My controller
public ActionResult A_Branch ()
{
string query = "SELECT BranchName,Name, MAX(A_STATUS) AS A_Status "
+ "FROM Students "
+ "WHERE BranchName= '1_Branch' "
+ "GROUP BY BranchName,Name";
IEnumerable<EnrollmentStudentGroup> data = db.Database.SqlQuery<EnrollmentStudentGroup>(query);
return View(data.ToList());
}
And the next actionresult which i'm going to create 23 times more.
public ActionResult B_Branch ()
{
string query = "SELECT BranchName,Name, MAX(A_STATUS) AS A_Status "
+ "FROM Students "
+ "WHERE BranchName= '2_Branch' "
+ "GROUP BY BranchName,Name";
IEnumerable<EnrollmentStudentGroup> data = db.Database.SqlQuery<EnrollmentStudentGroup>(query);
return View(data.ToList());
}
My 2 models;
public class Student : BaseEntity
{
public int Id { get; set; }
public string BranchName { get; set; }
public string Name { get; set; }
public int A_Status { get; set; }
}
public class EnrollmentStudentGroup
{
public string BranchName { get; set; }
public string Name { get; set; }
public int A_Status { get; set; }
public IEnumerable<EnrollmentStudentGroup> StudentCollection { get; set; }
}
and my Model
public class Model
{
public List<Student> Students { get; set; }
public List<EnrollmentStudentGroup> EnrollmentStudentGroup { get; set; }
}
My newest controller ( after " .select " he is giving me errors )
[HttpGet]
public ActionResult TestNew(string branchname)
{
// check stuff like permissions
var db = new MovieContext();
var model = new Model();
var students = db.Student
.Where(x => x.BranchName == branchname)
.GroupBy(x => new { x.BranchName, x.Name, x.Currency, x.NoCart, x.NoAccount })
.Select(x => new
{
BranchName = x.FirstOrDefault().BranchName,
Name = x.FirstOrDefault().Name,
A_Status = x.Max(p => p.A_Status),
Currency = x.FirstOrDefault().Currency,
NoCart = x.FirstOrDefault().NoCart,
NoAccount = x.FirstOrDefault().NoAccount
}).ToList();
foreach (var item in students)
{
model.Students.Add(new Student
{
A_Status = item.A_Status,
BranchName = item.BranchName,
Name = item.Name,
NoAccount = item.NoAccount,
NoCart = item.NoCart,
Currency = item.Currency
});
}
return View(model);
}
Now that error, i updated my model and view(cshtml) by your answer.
My view(cshtml)
#model Tessa.Models.Model
#{
ViewBag.Title = "BranchView";
}
<h2>BranchView</h2>
#foreach (var item in Model.Students)
{
<p>#item.Name</p>
<p>#item.A_Status</p>
<p>#item.BranchName</p>
<p>#item.NoAccount</p>
<p>#item.NoCart</p>
<p>#item.Currency</p>
}
As in the comments wrote you dont have to do this for every single branch. Here is a solutions which may help you
Your Controller
public ActionResult Branch(string branchname)
{
var db = new ApplicationDbContext();
var model = new Model();
var students = db.Students
.Where(x => x.BranchName == branchname)
.GroupBy(x => new { x.BranchName, x.Name, x.Currency, x.NoCart, x.NoAccount })
.Select(x => new
{
BranchName = x.FirstOrDefault().BranchName,
Name = x.FirstOrDefault().Name,
A_Status = x.Max(p => p.A_Status),
Currency = x.FirstOrDefault().Currency,
NoCart = x.FirstOrDefault().NoCart,
NoAccount = x.FirstOrDefault().NoAccount
}).ToList();
foreach (var item in students)
{
model.Students.Add(new Student
{
A_Status = item.A_Status,
BranchName = item.BranchName,
Name = item.Name,
NoAccount = item.NoAccount,
NoCart = item.NoCart,
Currency = item.Currency
});
}
return View(model);
}
So you only pass the branchname to the controller. Her are severale diffrent ways to do this.
Its good practice to have a model to pass to a view.
public class Model
{
public List<Student> Students { get; set; }
//Some other propertys
public Model()
{
Students = new List<Student>();
}
}
And finialy you can write your view like this
#model TestApp.Models.Model
#{
ViewBag.Title = "BranchView";
}
<h2>BranchView</h2>
#foreach (var item in Model.Students)
{
<p>#item.Name</p>
<p>#item.A_Status</p>
<p>#item.Branchname</p>
<p>#item.NoAccount</p>
<p>#item.NoCart</p>
<p>#item.Currency</p>
}
In the foreach-loop you can do normal html stuff. This will done for every element in your list.
I hope this help you.

The selected item in a listbox is null how can i fix that?

I am working on a listbox system that allows exercises in a regime to be deleted using a remove method in my controller. Currently when i select an item then click remove it returns an empty list of items and no changes are made to the db
At the moment ive got my code to produce no errors however currently after setting some breakpoints it appears that item in RemoveExercises is currently null. So i changed the line RegimeItem item = model.RequestedExercises.FirstOrDefault(i => i.RegimeItemID == selected); to RegimeItem item = model.RequestedSelected... and now i am recieving the error 'int' does not contain a definition for 'RegimeItemID' and no extension method 'RegimeItemID' accepting a first argument of type 'int' could be found
What i want to happen is the regime item that is selected is removed when the remove button is pressed.
Controller.cs
[HttpGet]
public ActionResult ExerciseIndex(int id, UserExerciseViewModel vmodel)
{
//Session["UserExerciseViewModel"] = userExerciseViewModel;
User user = db.Users.Find(vmodel.UserID);
//User user = db.Users.Find(id);
//vmodel.UserID = user.UserID;
UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
Session["UserExerciseViewModel"] = model;
return View(model);
}
//Post
[HttpPost]
public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id, RegimeItem item)
{
// model = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
//model.UserID = user.UserID;
User user = db.Users.Find(model.UserID);
user.RegimeItems = model.RequestedExercises;
UserExerciseViewModel model2 = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
model.RequestedExercises = model2.RequestedExercises;
model.AvailableExercises = model2.AvailableExercises;
if (!string.IsNullOrEmpty(add))
AddExercises(model, id);
else if (!string.IsNullOrEmpty(remove))
RemoveExercises(model, id);
SaveState(model);
RestoreSavedState(model, user);
return View(model);
}
void SaveState(UserExerciseViewModel model)
{
model.SavedRequested = string.Join(",", model.RequestedExercises.Select(p => p.RegimeItemID.ToString()).ToArray());
db.SaveChanges();
}
void RemoveExercises(UserExerciseViewModel model, int id)
{
var userExerciseViewModel = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
foreach (int selected in model.RequestedSelected)
{
RegimeItem item = model.RequestedExercises.FirstOrDefault(i => i.RegimeItemID == selected);
if (item != null)
{
User user = db.Users.Find(id);
model.RequestedExercises.Remove(item);
}
}
db.SaveChanges();
}
void AddExercises(UserExerciseViewModel model, int id)
{
var userExerciseViewModel = (UserExerciseViewModel)(Session["UserExerciseViewModel"]);
foreach (int selected in model.AvailableSelected)
{
if (model.AvailableSelected != null)
{
User user = db.Users.Find(id);
user.RegimeItems.Add(new RegimeItem()
{
RegimeExercise = (this.GetAllExercises().FirstOrDefault(i => i.ExerciseID == selected))
});
}
}
db.SaveChanges();
//RedirectToAction("ExerciseIndex");
}
void RestoreSavedState(UserExerciseViewModel model, User user)
{
user.RegimeItems = model.RequestedExercises;
//get the previously stored items
if (!string.IsNullOrEmpty(model.SavedRequested))
{
string[] exIds = model.SavedRequested.Split(',');
var regimeItems = ChosenExercises(user, model).Where(p => exIds.Contains(p.RegimeItemID.ToString()));
model.RequestedExercises.AddRange(regimeItems);
}
db.SaveChanges();
}
private List<Exercise> GetAllExercises()
{
return db.Exercises.ToList();
}
private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model)
{
return db.Users
.Where(u => u.UserID == user.UserID)
.SelectMany(u => u.RegimeItems)
.ToList();
}
Models(cs)
public class User
{
public int UserID { get; set; }
public ICollection<RegimeItem> RegimeItems { get; set; }
public User()
{
this.RegimeItems = new List<RegimeItem>();
}
}
public class RegimeItem
{
public int RegimeItemID { get; set; }
public Exercise RegimeExercise { get; set; }
}
ViewModel.cs
public class UserExerciseViewModel
{
public List<Exercise> AvailableExercises { get; set; }
public List<RegimeItem> RequestedExercises { get; set; }
public int? SelectedExercise { get; set; }
public int[] AvailableSelected { get; set; }
public int[] RequestedSelected { get; set; }
public string SavedRequested { get; set; }
}
View.cshtml(Segment only)
<input type="submit" name="remove"
id="remove" value="<<" />
</td>
<td valign="top">
#Html.ListBoxFor(model => model.RequestedSelected, new MultiSelectList(Model.RequestedExercises, "RegimeItemID", "RegimeExercise.Name", Model.RequestedSelected))
</td>
Your problem stems from the fact that your are attempting to get the RegimeItemID property of an int value; take a look at the following:
public int[] RequestedSelected { get; set; }
RegimeItem item = model.RequestedSelected.FirstOrDefault(i => i.RegimeItemID == selected);
You basically tell LINQ to try to use the .RegimeItemID of the int iterator of the int[] array.
If I am not mistaken about your structure, you should change the
RegimeItem item = model.RequestedSelected.FirstOrDefault(i => i.RegimeItemID == selected);
to:
RegimeItem item = model.RequestedExercises[selected];
in that loop.
foreach (int selected in model.RequestedSelected)
//foreach (var item in new ArrayList(model.RequestedExercises.RegimeItemID))
{
RegimeItem item = model.RequestedExercises[selected];
if (item != null)
{
model.RequestedExercises.Remove(item);
db.SaveChanges();
}
}
Edit:
New information provided: the code in the question is infact the right code, however the problem lies with the RestoreSavedState method which should look more along the lines of:
void RestoreSavedState(UserExerciseViewModel model, User user)
{
user.RegimeItems = model.RequestedExercises;
//get the previously stored items
if (!string.IsNullOrEmpty(model.SavedRequested))
{
string[] exIds = model.SavedRequested.Split(',');
var regimeItems = ChosenExercises(user, model).Where(p => exIds.Contains(p.RegimeItemID.ToString()));
model.RequestedExercises.AddRange(regimeItems);
}
}

Binding DropDownList in Mvc and Get Selected Value

my Model is
public class ChildMenu
{
public string Name { get; set; }
public string Comments { get; set; }
public List<UlrikenModel.ulriken_tblChildMenu> FormDetails { get; set; }
public long pkChildMenuID { get; set; }
public long fkSubMenuID { get; set; }
[Required(ErrorMessage = "Requird")]
public string ChildManuName { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string Events { get; set; }
public IList<SelectListItem> Drp_Submenu { get; set; }
}
My Controller action is :
public ActionResult FillDeptName()
{
UlrikenEntities db1 = new UlrikenModel.UlrikenEntities();
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-Please select-", Value = "Selects
items" });
var cat = (from c in db1.ulriken_tblSubMenu where c.fkMainMenuID == 1 &&
c.Status == true select new { c.pkSubMenuID,c.SubManuName }).ToArray();
for (int i = 0; i < cat.Length; i++)
{
list.Add(new SelectListItem
{
Text = cat[i].SubManuName,
Value = cat[i].pkSubMenuID.ToString(),
Selected = (cat[i].pkSubMenuID == 1)
});
}
ViewBag.list = list;
return View("ChildMenuOfSubMenu", ViewBag.list);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult ChildMenuOfSubMenu(ChildMenu obj)
{
UlrikenEntities db = new UlrikenEntities();
ulriken_tblChildMenu objchild = new ulriken_tblChildMenu();
objchild.fkSubMenuID = obj.fkSubMenuID;
objchild.ChildMenuName = obj.ChildManuName;
objchild.cPageBody = obj.Name;
db.ulriken_tblChildMenu.Add(objchild);
db.SaveChanges();
return View("ChildMenuOfSubMenu");
}
and view is
#Html.DropDownListFor(m=>m.fkSubMenuID,
(IEnumerable<SelectListItem>)ViewBag.list,"Select" ,new { id = "ddlSubMenu" })
At start dropdown bind successfully but after saving data to database show an exception in
as "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key
'fkSubMenuID'"
AnyBody guide me where am i doing wrong.
Move that code to the helper class:
public class ControllerHelper
{
public List<SelectListItem> FetchListItems()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var cat = (from c in db1.ulriken_tblSubMenu where c.fkMainMenuID == 1 &&
c.Status == true select new { c.pkSubMenuID,c.SubManuName }).ToArray();
for (int i = 0; i < cat.Length; i++)
{
list.Add(new SelectListItem
{
Text = cat[i].SubManuName,
Value = cat[i].pkSubMenuID.ToString(),
Selected = (cat[i].pkSubMenuID == 1)
});
}
return list;
}
}
And then your controller should looks like:
public ActionResult FillDeptName()
{
UlrikenEntities db1 = new UlrikenModel.UlrikenEntities();
ViewBag.list = new ControllerHelper().FetchListItems();
return View("ChildMenuOfSubMenu", ViewBag.list);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult ChildMenuOfSubMenu(ChildMenu obj)
{
UlrikenEntities db = new UlrikenEntities();
ulriken_tblChildMenu objchild = new ulriken_tblChildMenu();
objchild.fkSubMenuID = obj.fkSubMenuID;
objchild.ChildMenuName = obj.ChildManuName;
objchild.cPageBody = obj.Name;
db.ulriken_tblChildMenu.Add(objchild);
db.SaveChanges();
ViewBag.list = new ControllerHelper().FetchListItems();
return View("ChildMenuOfSubMenu");
}
Of course:
new ControllerHelper().FetchListItems();
should be a field in the controller class, for example:
private ControllerHelper controlerHelper;
You can use Interface instead of concerete implementation, if you use DI.
Regards

Categories