How to Bring Child's Name to List? - asp.net-mvc

enter image description hereI intend to return the name of the child with the vaccines already administered.
what happens is that it does not return anything to me, since if I call the Id it returns the Id of the Child
Model VacinacaoIndexData
using GestCentros.Models;
using System.Collections.Generic;
namespace GestCentros.ViewModels
{
public class VacinacaoIndexData
{
public IEnumerable<Vacinacao> Vacinacoes { get; set; }
public IEnumerable<Vacina> Vacinas { get; set; }
public IEnumerable<Enrollment> Enrollments { get; set; }
}
}
Controler
public ActionResult Index(int? id, int? Idvacina)
{
var user = db.Users.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
if (user == null)
{
return RedirectToAction("Index", "Home");
}
var viewModel = new VacinacaoIndexData();
viewModel.Vacinacoes = db.Vacinacao
.Include(v => v.Vacinas)
.Include(v => v.Crianca)
.Where(c => c.IdCentro == user.IdCentro);
if (id != null)
{
ViewBag.IdVacinacao = id.Value;
viewModel.Vacinas = viewModel.Vacinacoes
.Single(i => i.IdVacinacao == id.Value).Vacinas;
}
if (Idvacina == null) return View(viewModel);
ViewBag.IdVacina = Idvacina.Value;
// Lazy loading
viewModel.Enrollments = viewModel.Vacinas.Single(x => x.IdVacina == Idvacina).Enrollments;
// Explicit loading
Vacina selectedVacina = viewModel.Vacinas.Single(x => x.IdVacina == Idvacina);
db.Entry(selectedVacina).Collection(x => x.Enrollments).Load();
foreach (var enrollment in selectedVacina.Enrollments)
{
db.Entry(enrollment).Reference(x => x.Centro).Load();
}
viewModel.Enrollments = selectedVacina.Enrollments;
return View(viewModel);
}
In the Field Name I would like to Show Child Name, but it does not return anything
#model GestCentros.ViewModels.VacinacaoIndexData
#{
ViewBag.Title = "Index";
}
<h2 class="text-center">Lista de Crianças Vacinadas</h2>
<table class="table">
<tr>
<th>Nome</th>
<th>Data Vacinação</th>
<th>Vacinas</th>
<th>Operações</th>
</tr>
#foreach (var item in Model.Vacinacoes)
{
string selectedRow = "";
if (item.IdVacinacao == ViewBag.IdVacinacao)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.DisplayFor(model => item.Crianca.Nome)
</td>
<td>
#item.DataVacina.ToString("dd/MM/yyyy")
</td>
<td>
#{
foreach (var vacina in item.Vacinas)
{
#: #vacina.Nome <br />
}
}
</td>
</tr>
}
</table>
#if (Model.Vacinas != null)
{
<h3>Vacinas Ministradas na Campanha</h3>
<table class="table">
<tr>
<th>Operações</th>
<th>Vacina</th>
</tr>
#foreach (var item in Model.Vacinas)
{
var selectedRow = "";
if (item.IdVacina == ViewBag.IdVacina)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Selecionar", "Index", new { IdVacina = item.IdVacina }, new { #class = "btn btn-sm btn-secundary" })
| #Html.ActionLink("Voltar a Lista", "Index", new { }, new { #class = "btn btn-sm btn-default" })
</td>
<td>
#item.Nome
</td>
</tr>
}
</table>
}
#if (Model.Enrollments != null)
{
<h3>
Students Enrolled in Selected Course
</h3>
<table class="table">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
#foreach (var item in Model.Enrollments)
{
<tr>
<td>
#item.Centro.Name
</td>
<td>
#Html.DisplayFor(modelItem => item.Grade)
</td>
</tr>
}
</table>
}

Related

.NET MVC JQuery function is not getting fired in table row click event

I have table data in UI. I want to display data in a div in the same page when I click the Details link in the row. The JQuery function is not getting fired in when I click on details link in any row.
Below is my code:
Model view class:
public class ItemViewModel
{
public Item item { get; set; }
public IEnumerable<Item> items { get; set; }
}
UI Code:
#model Medhub.Models.ItemViewModel
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>View</h2>
<p>
#Html.ActionLink("Create New", "CreateEdit", new { controller = "Item" }, new { #class = "btn btn-primary" })
</p>
<table align="center" height="10%" width="90%">
<tr>
<td>
<div id="Items">
<table style="vertical-align:top; height:200px" width="100%">
<tr style="height:20px">
<th>
#Html.DisplayName("Name")
</th>
<th>
#Html.DisplayName("Description")
</th>
<th>
#Html.DisplayName("Item Type")
</th>
</tr>
#if (Model != null)
{
foreach (var item in Model.items)
{
<tr style="height:15px">
<td>
#Html.HiddenFor(model => item.ItemId)
#Html.DisplayFor(model => item.Name)
</td>
<td>
#Html.DisplayFor(model => item.Description)
</td>
<td>
#Html.DisplayFor(model => item.Type)
</td>
<td>
#Html.ActionLink("Edit", "CreateEdit", new { id = item.ItemId }) |
#Html.ActionLink("Details", "Item", new { id = item.ItemId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ItemId })
</td>
</tr>
}
}
</table>
</div>
</td>
</tr>
</table>
<table>
<tr>
<td>
<div id="ItemDetails">
#if (Model.item != null)
{
Html.RenderPartial("Details", Model.item);
}
</div>
</td>
</tr>
</table>
<script type="text/javascript">
$(function () {
$("div.Items a").click(function (e) {
//e.preventDefault();
var url = this.ref;
$("#ItemDetails").load(url);
});
});
</script>
Controller code:
List<Item> items = new List<Item>();
// GET: Item
public ActionResult Item(int id = 0)
{
ItemViewModel itemVM = new ItemViewModel();
itemVM.items = GetItems();
if (id > 0)
itemVM.item = itemVM.items.FirstOrDefault(u => u.ItemId == id);
return View(itemVM);
}
Any clues?
First of all, you are waiting for clicks on a class called Items. This is the reason the jquery code is not being fired. You should have
$("div#Items a").click(function (e) {
Secondly, you need to check the attribut href, not ref. Also, prevent default needs to be there, otherwise you just reload your page
e.preventDefault();
var url = this.href;
You don't need the renderpartial in the page, just leave it empty:
<div id="ItemDetails">
</div>
While your logic kind of works, the way the url is loaded causes the entire page to be loaded into the ItemDetails section. I'd suggest that in your controller, you'd create a separate method for the details:
public ActionResult Details(int id) {
Item item = GetItem(id);
return View(item);
}
private Item GetItem(int id) {
return new Item() { Details = "details here" };
}

Replace string in Razor View

I would like to replace a string into Razor view and for some reason it does not work
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.User)</td>
<td>#Html.DisplayFor(modelItem => item.PasswordExpired.Replace("True", "Yes"))</td>
</tr>
}
Property PasswordExpired is a bool.
Any help would be appreciated.
It works nice with this code
#foreach (var item in Model)
{
<tr>
<td nowrap="">#Html.DisplayFor(modelItem => item.User)</td>
#{
if (item.PasswordExpired != null)
{
string isPasswordExpired = item.PasswordExpired.Replace("True", "Yes").Replace("False", "No");
<td>#isPasswordExpired</td>
}
else
{
string isPasswordExpired = "";
<td>#isPasswordExpired</td>
}
}
</tr>
}

lambda expression Problems

My question is when I click actionlink,the view send specific ID to controller(ex. ProductID = 6), but my controller grab all data to me not specific ID data.
I think the problem is the lambda expression at controller, it will grab all data to me.
These are my Models:
public class ShoppingCart
{
public List<ShoppingCartItemModel> items = new List<ShoppingCartItemModel>();
public IEnumerable<ShoppingCartItemModel> Items
{
get { return items; }
}
}
public class ShoppingCartItemModel
{
public Product Product
{
get;
set;
}
public int Quantity { get; set; }
}
Controller :
[HttpGet]
public ActionResult EditFromCart(int ProductID)
{
ShoppingCart cart = GetCart();
cart.items.Where(r => r.Product.ProductID == ProductID)
.Select(r => new ShoppingCartItemModel
{
Product = r.Product,
Quantity = r.Quantity
});
return View(cart);
//return RedirectToAction("Index", "ShoppingCart");
}
private ShoppingCart GetCart()
{
ShoppingCart cart = (ShoppingCart)Session["Cart"];
//如果現有購物車中已經沒有任何內容
if (cart == null)
{
//產生新購物車物件
cart = new ShoppingCart();
//用session保存此購物車物件
Session["Cart"] = cart;
}
//如果現有購物車中已經有內容,就傳回 view 顯示
return cart;
}
View
#model ShoppingCart
#{
ViewBag.Title = "購物車內容";
}
<h2>Index</h2>
<table class="table">
<thead>
<tr>
<th>
Quantity
</th>
<th>
Item
</th>
<th class="text-right">
Price
</th>
<th class="text-right">
Subtotal
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.items)
{
<tr>
<td class="text-center">
#item.Quantity
</td>
<td class="text-center">
#item.Product.ProductName
</td>
<td class="text-center">
#item.Product.Price.ToString("c")
</td>
<td class="text-center">
#( (item.Quantity * item.Product.Price).ToString("c"))
</td>
<td>
#using (Html.BeginForm("RemoveFromCart", "ShoppingCart"))
{
#Html.Hidden("ProductId", item.Product.ProductID)
#*#Html.HiddenFor(x => x.ReturnUrl)*#
<input class="btn btn-warning" type="submit" value="Remove">
}
</td>
<td>
#using (Html.BeginForm("EditFromCart", "ShoppingCart", FormMethod.Get))
{
#Html.Hidden("ProductId", item.Product.ProductID)
<input class="btn btn-warning" type="submit" value="Edit">
}
</td>
</tr>
}
</tbody>
</table>
The key issue is that this code doesn't return the result of the LINQ queries, because you have not assigned a variable to the result:
cart.items.Where(r => r.Product.ProductID == ProductID)
.Select(r => new ShoppingCartItemModel
{
Product = r.Product,
Quantity = r.Quantity
});
I strongly suggest you create a viewmodel specifically to display the cart items.
public class CartItemsViewModel
{
public List<ShoppingCartItemModel> Items { get; set; }
}
[HttpGet]
public ActionResult EditFromCart(int ProductID)
{
ShoppingCart cart = GetCart();
var viewModel = new CartItemsViewModel();
viewModel.Items.AddRange(cart.items.Where(r => r.Product.ProductID == ProductID)
.Select(r => new ShoppingCartItemModel
{
Product = r.Product,
Quantity = r.Quantity
}));
return View(viewModel);
}
In my example I use the .AddRange() method to take the results of the LINQ calls against the cart items and store them in the viewmodel's Items property.
You must have to assign filtered value to cart like this.
cart.item = cart.items.Where(r => r.Product.ProductID == ProductID)
.Select(r => new ShoppingCartItemModel
{
Product = r.Product,
Quantity = r.Quantity
}).ToList();
use ToList(); or FirstOrDefault() as per your condition
You need to hold the return value from the linq query on cart.Items in a variable and pass that to the View method.
At the moment, the result of your query is being lost and the whole cart passed to the View method.

Modifying the text color and background color of a table

I no longer have a question as I figured out how to do it
Index.cshtml
#model IEnumerable<ContactManager.Models.Contacts>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2></h2>
#using (Html.BeginForm()) {
<p>#Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.City)
</th>
<th>
#Html.DisplayNameFor(model => model.State)
</th>
<th>
#Html.DisplayNameFor(model => model.Zip)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<th>
Modify
</th>
</tr>
#foreach (var item in Model) {
var lncolor = "white" ;
var zipcolor = "black";
switch (item.LastName) {
case "Whited":
lncolor = "yellow";
break;
default:
lncolor = "white";
break;
}
if (item.ID % 2 == 0) {
zipcolor = "red";
} else {
zipcolor = "black";
}
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td bgcolor="#lncolor">
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
<font color="#txtcolor">
#Html.DisplayFor(modelItem => item.Zip)
</font>
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
Relative part of my Controller
private ContactsDBContext db = new ContactsDBContext();
// GET: Contacts
public ActionResult Index(string searchString)
{
var contacts = from c in db.Contact
select c;
if (!String.IsNullOrEmpty(searchString)) {
contacts = contacts.Where(s => s.FirstName.Contains(searchString) || s.LastName.Contains(searchString) || s.Address.Contains(searchString)
|| s.City.Contains(searchString) || s.State.Contains(searchString) || s.Zip.Contains(searchString) || s.Phone.Contains(searchString));
}
//return View(db.Contact.ToList());
return View(contacts);
}
I managed to figured out a way to accomplish what I wanted to do with this. I have updated the code as well to refelct on what I have done. I am not sure it is the most elegant way to accomplish this so if anyone has any better suggestions I am all ears.
Writing any kind of logic in view page is highly depreciated in MVC pattern. You can do it by using viewmodel. Here is the steps.
First create an appropriate view model for model contact.
public class ContactViewModel
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public string Address{ get; set; }
public string City{ get; set; }
public string State{ get; set; }
public string Zip{ get; set; }
public string Phone{ get; set; }
public string LastNameBgcolor{ get; set; }
public string FontColor{ get; set; }
}
In controller:
private ContactsDBContext db = new ContactsDBContext();
// GET: Contacts
public ActionResult Index(string searchString)
{
var contacts = from c in db.Contact
select c;
if (!String.IsNullOrEmpty(searchString)) {
contacts = contacts.Where(s => s.FirstName.Contains(searchString) || s.LastName.Contains(searchString) || s.Address.Contains(searchString)
|| s.City.Contains(searchString) || s.State.Contains(searchString) || s.Zip.Contains(searchString) || s.Phone.Contains(searchString));
}
//return View(db.Contact.ToList());
List<ContactViewModel> ContactViewModels= new List<ContactViewModel>();
foreach(var contact in contacts){
ContactViewModel cvm= new ContactViewModel();
cvm.FirstName=contact.FirstName;
cvm.LastName=contact.LastName;
if(contact.LastName=="Whited"){
cvm.LastNameBgcolor="yellow";
}
else{
cvm.LastNameBgcolor="white";
}
cvm.Address=contact.Address;
cvm.City=contact.City;
cvm.State=contact.State;
cvm.Zip=contact.Zip;
cvm.Phone=contact.Phone;
if (contact.ID % 2 == 0) {
cvm.FontColor = "red";
} else {
cvm.FontColor = "black";
}
ContactViewModels.Add(cvm);
}
return View(ContactViewModels);
}
In view page:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td bgcolor="#model.LastNameBgcolor">
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
<font color="#model.FontColor">
#Html.DisplayFor(modelItem => item.Zip)
</font>
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
Hope this will help.

Search by multiple values

How can i make my search engine accept inputs more than one which are seperated by comma?
This is my index.view:
<p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<b>Search by:</b> #Html.RadioButton("searchby", "ItemID", true)<text>Item Id</text>
<br />
#Html.TextBox("search") <input type="submit" value="Search" />
}
</p>
<table>
<tr>
<th>
ItemID
</th>
<th>
Item name
</th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan="2">no item id found.</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.itemid)
</td>
<td>
#Html.DisplayFor(modelItem => item.itemname)
</td>
</tr>
}
<caption>Total #Html.Encode(Model.Count()) item found.</caption>
}
</table>
And this is my homecontroller.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using itemdb.Models;
namespace itemdb.Controllers
{
public class HomeController : Controller
{
private mydbEntities db = new mydbEntities();
public ActionResult Index(string searchBy, string search)
{
if (!String.IsNullOrEmpty(searchBy) && !String.IsNullOrEmpty(search))
{
if (searchBy == "itemid")
{
return View(db.itemlist.Where(x => x.items == search).ToList());
}
else
{
return View(db.itemlist.Take(0));
}
}
}
}
public ActionResult Index(string searchBy, string search)
{
if (!String.IsNullOrEmpty(searchBy) && !String.IsNullOrEmpty(search))
{
string[] items = search.Split(new Char[] {','});
if (searchBy == "itemid")
{
return View(db.itemlist.Where(x => items.Contains(x.items)).ToList());
}
else
{
return View(db.itemlist.Take(0));
}
}

Resources