Replace string in Razor View - asp.net-mvc

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>
}

Related

How to Bring Child's Name to List?

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>
}

save all tr elements of a table with checkbox and send it to the controller , in MVC 4

I am new to MVC and now stuck in a serious problem. it is for me, very serious
I need to load a view with a list of meetings (which is loading fine) in html , I have added a checkbox to each row also. Now I need to save to the database ,only the checked values. But the controller is returning null when posting.. Really stuck and cant find a solution.
Pls see code below which I have done
Model
public class aMeet
{
public List<AcceptedRecords> amList { get; set; }
public static List<AcceptedRecords> GetamList()
{
DataSet ds = new DataSet();
List<AcceptedRecords> resultlist = new List<AcceptedRecords>();
using (cmd)
{
cmd.CommandText = #"SELECT Line_code,person_code,person_address from tbl where meeting_code =859489;
ds = cmd.ExecuteDataSet();
}
if (!Utils.IsDataSetEmpty(ds))
{
AcceptedRecords tpmApp;
foreach (DataRow row in ds.Tables[0].Rows)
{
tpmApp = new AcceptedRecords();
tpmApp = tpmApp.LoadRecords(row);
resultlist.Add(tpmApp);
}
}
return resultlist;
}
}
Model
public class AcceptedRecords
{
public int line_Code { get; set; }
public string person_Name { get; set; }
public string person_Address { get; set; }
public bool extra_checked { get; set; }
}
View
#model projct.Models.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table id="tbl" style ="width:100%" cellpadding="0" cellspacing="0" class="race-fields">
<thead>
<tr>
<th style="width:500px">line code</th>
<th style="width:100px">name</th>
<th style="width:500px">address</th>
<th style="width:500px">extra</th>
</tr>
</thead>
<tbody>
<tr>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_name) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_address) </td>
<td>
#Html.CheckBoxFor(m => m.amList[i].extra_checked) </td>
</tr>
}
</tr>
<tr>
<span>
<input type="submit" Value ="Save"/>
</span>
</tr>
</tbody>
</table>
}
Controller
[HttpPost]
public ActionResult AddRecord(List<aMeet> spm)
{
if (spm == null)
throw new ApplicationException("No Parameters passed to Create");
int? appID = 0;
return Json(appID);
}
}
--- It Is triggering to controller on Save but model [spm] is null.
How to get this corrected. Here I need to save to database the tr elements that are checked. Please request any help. I have tried a lot of things but the model is always null/
Many thanks
Assuming your aRecs class has a amList property which is a list of AcceptedRecords
public class aRecs
{
public List<AcceptedRecords> amList { set; get; }
}
Assuming line_code value is a unique (may be primary key) to get a record from your corresponding table, In your view, you need to keep the line_code property value of each item in amList in a hidden field so that when the form is submitted you will get this value and using that you can query the corresponding record and update it.
#model YourNamespaceHere.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code)
</td>
<td>#Html.DisplayFor(m => m.amList[i].person_Name) </td>
<td>
#Html.CheckBoxFor(m=>m.amList[i].extra_checked)
#Html.HiddenFor(m => m.amList[i].line_Code)
</td>
</tr>
}
</table>
<input type="submit"/>
}
And in your HttpPost action, your parameter will be a single object of aRecs
[HttpPost]
public ActionResult AddRecord(aRecs model)
{
foreach (var item in model.amList)
{
var lineCode = item.line_Code;
var isChecked = item.extra_checked;
/// get the record using lineCode and update the record.
}
return RedirectToAction("Index");
}

Writing conditional HTML with razor

Depending on my record, I'd like to change the style of the table row in my current iteration.
The below example doesn't work, but how would I go about doing this correctly?
foreach (var item in Model)
{
#{
if (item.DataState != DataState.Active)
{
<tr style="background-color: red">
}
else
<tr>
}
<td>#item.Name</td>
</tr>
}
So effectively, I'd like to dynamically render the <tr> element differently based on the DataState of my model.
Here's a shorter approach:
#foreach (var item in Model)
{
<tr #(item.DataState != DataState.Active ? "style=background-color:red" : "")>
<td>#item.Name</td>
</tr>
}
Edit: Code fixed
There are multiple way you can write condition.
Option 1:
#foreach (var item in Model)
{
if (item.DataState != DataState.Active)
{
<tr style="background-color: red">
<td>#item.Name</td>
</tr>
}
else
{
<tr>
<td>#item.Name</td>
</tr>
}
}
Option 2:
#foreach (var item in Model)
{
<tr style="#( item.DataState != DataState.Active ? "background-color: red;" : "" )">
<td>#item.Name</td>
</tr>
}
Define the attributes in a variable. The razor parser will omit the attribute if its value is null
#foreach (var item in Model)
{
var attributes = item.DataState == DataState.Active ? null : "background-color: red";
<tr style=#attributes>
<td>#item.Name</td>
</tr>
}
Not sure what kind of error you faces right now, but i gess your problem is that Razor don't understand all cases of tricky html render.
You can force him to render html where you need with #: symbol for single string or <text> tag like this:
#foreach (var item in Model)
{
if (item.DataState != DataState.Active)
{
#: <tr style="background-color: red">
}
else
{
<text><tr></text>
}
<td>#item.Name</td>
</tr>
}
You're probably going to get compile errors if you start splitting the <tr> tag up in the view and I'd not duplicate large chunks of code. I would do the following:
#foreach(var item in Model) {
string strStyle=String.Empty;
if(item.DataState!=DataState.Active) { strStyle = "background-color:red;" }
<text>
<tr style="#strStyle">
<td>#item.Name</td>
</tr>
</text>
}
#(item.DataState != DataState.Active ? "style=" + "background-color:red" : "")
#(!string.IsNullOrWhiteSpace(Model?.District?.Name) ? Html.Raw($"<span class=\"location\">{Model?.District?.Name}</span>") : string.Empty)

Error on listing the elements

I am getting the following error
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType34[System.String,System.Int32,System.Int32,System.DateTime]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ControllerName]'.
I did the code migration (database update) after that I want to just list the items by column name My code is as follows
public ActionResult Index()
{
DB db = new DB();
var categorylist = from a in db.categories
select new
{
a.CategoryName,
a.ID,
a.stock,
a.EntryDate
};
return View(categorylist.ToList());
}
Any help would be appreciated
Thanks in advance.
View is as follows
#model IEnumerable<Categories.Models.Categories>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create") </p> <table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.CategoryName)</th>
<th>#Html.DisplayNameFor(model => model.stock)</th>
<th>#Html.DisplayNameFor(model => model.EntryDate)</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.CategoryName)</td>
<td>#Html.DisplayFor(modelItem => item.stock)</td>
<td>#Html.DisplayFor(modelItem => item.EntryDate)</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
To take advantage of the model binding features of MVC you should create a view model which represents those the properties you want to display and/or edit (adjust property types as required)
public class CategoryVM
{
public int ID { get; set; }
public string CategoryName { get; set; }
public int Stock { get; set; }
public DateTime EntryDate { get; set; }
}
and change you method to
public ActionResult Index()
{
DB db = new DB();
var categorylist = (from a in db.categories
select new CategoryVM
{
CategoryName = a.CategoryName,
ID = a.ID,
Stock = a.stock,
EntryDate = a.EntryDate
}).ToList();
return View(categorylist);
}
View
#model List<CategoryVM>
<table>
<thead>
<tr>
<th>Category Name</th>
<th>stock</th>
<th>Entry Date</th>
...
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<td>#Html.DisplayFor(m => item.ID)<td>
<td>#Html.DisplayFor(m => item.CategoryName)</td>
...
</tr>
}
</tbody>
</table>
I think you need to Change the model type thar you defined in your view
Edit: Try
#model IList<dynamic>

The model item passed is of type 'System.Collections.Generic.List but this dictionary requires 'System.Collections.Generic.IEnumerable

I am newbie and getting the error model item passed into directory is of type system.cllection.generic.list but this directory requires system.collection.ienumerable
Please help me to resolve this error.
I am pasting my controller and view here
Controller
public ActionResult DisplayComment()
{
var result = Manager.GetUsersWhoHaveConsumedFreeCredit();
JavaScriptSerializer serializer = new JavaScriptSerializer();
var callHistory = serializer.Deserialize<List<CallHistory>>(result);
YelloAdminDbContext db = new YelloAdminDbContext();
if (callHistory != null)
{
foreach (var item in callHistory.ToList())
{
int Id = int.Parse(item.Login);
var note = db.Note.OrderByDescending(i => i.Id).Where(i => i.LoginId == Id).FirstOrDefault();
if (note != null && note.LoginId == Id)
{
var temp = note.Comments.ToList();
return PartialView(temp);
}
else
return Content("No Comments");
}
}
return Content("No Comments");
}
View
#model IEnumerable<MyYello.Admin.Models.CallNote>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Comments)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Comments)
</td>
</tr>
}
</table>
Here you are reuturning List of type Commments:
var temp = note.Comments.ToList();
return PartialView(temp);
while in your view is strongly typed to Model of type IEnumerable<MyYello.Admin.Models.CallNote>
In View you have written, so it conflicts you View is expecting different type while you are passing different type:
#model IEnumerable<MyYello.Admin.Models.CallNote>
you should be returning IEnumerable<MyYello.Admin.Models.CallNote> from your action or if you need to pass Comments type then change in View :
#model List<MyYello.Admin.Models.Comments>

Resources