Would you kindly help me to get the desired output please? I am using .NET Core 3.1.
My function:
private List<Phrases_Clp> PhrasesStringToListPhrases_Clp(string phrases_codes)
{
var listprhases = phrases_codes != null ? phrases_codes.Split(",") : new string[0];
return _context.Phrases_Clps.Where(x => listprhases.Contains(x.Phrase_Numero)).ToList();
}
//GET: EvaluationRisque/Create
[Authorize(Roles = "Administrateur, Modificateur")]
public async Task<IActionResult> Create()
{
Create_Viewbags();
var model = new EvaluationRisquesViewModel();
var produitUtiliseByProduitId = await _context.Identification_Produit.FirstOrDefaultAsync();
model.MentionsDanger = produitUtiliseByProduitId;
model.List_Mentions_Danger = PhrasesStringToListPhrases_Clp(model.MentionsDanger.Mentions_Danger);
return View(model);
}
<td>
#foreach (var mention_danger in Model.List_Mentions_Danger)
{
<p> #mention_danger.Phrase_Numero : #mention_danger.Phrase_Libelle
</p>
}
</td>
Table identification_produit:
Id
Mentions_Danger
1
H203,H204
2
H203,H204,H205
3
H201,H202,H203
Table: phrases_clp
Phrase_Numero
Phrase_Libelle
H203
Explosif; danger d'incendie, d'effet de souffle ou de projection
H204
Danger d'incendie ou de projection
H201
Explosif; danger d'explosion en masse
Desired output:
Id
Mentions_Danger
1
H203:Explosif; danger d'incendie, d'effet de souffle ou de projection H204: Danger d'incendie ou de projection
2
H203Explosif; danger d'incendie, d'effet de souffle ou de projection H204: Danger d'incendie ou de projection, H205:aaaaaaaaaaaaaa
3
H201:bbbbbbbbbbbbbb, H202:ccccccccccccccccccc, H203:ddddddddddddddd
#Jérôme DE PORRES
I tried as below:
public class IdentificationProduit
{
public int Id { get; set; }
public string MentionsDanger { get; set; }
public List<PhrasesClp> PhrasesClps { get; set; }
}
public class PhrasesClp
{
[Key]
public string PhraseNumero { get; set; }
public string PhraseLibelle { get; set; }
public List<IdentificationProduit> IdentificationProduits { get; set; }
}
In controller:
var IdentificationProduits = _context.IdentificationProduit.Include(x=>x.PhrasesClps).ToList();
return View(IdentificationProduits);
In View:
#model List<IdentificationProduit>
<table>
<tr>
<th>Id</th>
<th>Mentions_Danger</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>
#for (int i = 0; i< item.PhrasesClps.Count; i++)
{
#string.Format("{0}:{1},", item.PhrasesClps[0].PhraseNumero, item.PhrasesClps[0].PhraseLibelle);
}
</td>
</tr>
}
</table>
DataBase:
Result:
I have a table in my Blazor Asp.Net 5 application with 4 columns:
Title
Quantity
Price
Total
Each time a user enters a price in column 3, I want the column 4 cell to be updated live by 3x2 (quantity X price) for the row in which he types it. How can I achieve this?
There may be many rows and data arrives from database.
Data is displayed to user and allows him to enter prices for each product row, meanwhile quantity is already populated:
#for (var i = 0; i < advert.Products.Count; i++)
{
var index = i;
var item = advert.Products[i];
<tr>
<th scope="row">#index</th>
<td>#item.Title</td>
<td>#item.Qty</td>
<td><input /></td>
<td>Sum here</td>
</tr>
}
#code {
[Parameter] public int AdvertId { get; set; }
public Advert advert;
protected override async Task OnInitializedAsync()
{
advert = await adRepo.GetAdvert(AdvertId);
}
}
Here is a working demo like below:
Model:
public class Advert
{
public int Id { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
public string Title { get; set; }
public int Qty { get; set; }
public int Price { get; set; }
}
Index.razor:
#for (var i = 0; i < advert.Products.Count; i++)
{
var index = i;
var item = advert.Products[i];
<tr>
<th scope="row">#index</th>
<td>#item.Title</td>
<td>#item.Qty</td>
<td><input #bind="#item.Price" /></td>
<td>#{
var total = item.Price * item.Qty;
}
#total</td>
</tr>
}
#code {
[Parameter] public int AdvertId { get; set; }
public Advert advert;
protected override async Task OnInitializedAsync()
{
advert = await adRepo.GetAdvert(AdvertId);
}
}
Result:
I'm trying to set values to table containing textboxes in each cell. For instance a table having a first column containing names, and rest of the columns containing textboxes to add marks of the given assignment for individual students. For that I used dictionary to hold given marks by the instructor and when the page is load, the marks are set to the relevant textboxes. however my iteration over Dictionary in jquery doesn't seem to be really working. I'm missing somewhere in loop. Below is my code.
public class StudentAssignments
{
public string Id { get; set; }
public Models.Assignment assignment { get; set; }
public Models.User user { get; set; }
public DateTime? SubmissionDate { get; set; }
public string Result { get; set; }
public Models.File assignmentfiles {get;set;}
}
public class Assignment
{
public string Id { get; set; }
public string batchid { get; set; }
public List<SelectListItem> batchnumber { get; set; }
public string Title { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime? DueDate { get; set; }
public Models.File file { get; set; }
}
public class File
{
public string strId { get; set; }
public string strName { get; set; }
public string strPath { get; set; }
public string strSize { get; set; }
}
InstructorController.cs
[HttpPost]
public ActionResult AssignedStudents(string id)
{
//Get Student Assignments
Models.StudentAssignments studentAssignment = new Models.StudentAssignments();
Context.Assignment contAssignment = new Context.Assignment();
CreateUser contUser = new CreateUser();
Dictionary<string, Dictionary<string, List<Models.StudentAssignments>>> dict =
new Dictionary<string, Dictionary<string, List<Models.StudentAssignments>>>();
var studentslist = contStudent.getAllStudentBatchList().Where(p => p.batchId == id).Select(p => p.studentId).ToList();
var assignmentid = contAssignment.lstAssignment().Where(p => p.batchid == id).Select(p=>p.Id).ToList();
foreach(var items in studentslist)
{
dict.Add(items.ToString(), new Dictionary<string, List<Models.StudentAssignments>>());
foreach (var item1 in assignmentid)
{
dict[items].Add(item1.ToString(), GetStudentFiles(items, item1));
}
}
ViewBag.StudentAssignment = dict;
}
private List<Models.StudentAssignments> GetStudentFiles(string stdid, string assgnid)
{
Context.Assignment contAssignment = new Context.Assignment();
CreateUser contuser = new CreateUser();
List<Models.StudentAssignments> lstassgn = new List<Models.StudentAssignments>();
var details = (from t1 in contAssignment.GetStudentAssignments()
join
t2 in contAssignment.GetStudentAssignmentsFiles() on
t1.Id equals t2.assignment.Id
join t3 in contuser.GetAllUsers() on t1.user.Id equals t3.Id
where t1.assignment.Id == assgnid && t1.user.Id == stdid
select new { t1,t2,t3 }).ToList();
foreach (var item in details)
{
Models.StudentAssignments assignment = new Models.StudentAssignments();
assignment.assignment = new Models.Assignment();
assignment.Id = item.t1.Id;
assignment.Result = item.t1.Result;
assignment.assignmentfiles = new Models.File();
assignment.assignmentfiles.strId = item.t2.Id;
assignment.assignmentfiles.strPath = item.t2.assignmentfiles.strPath;
assignment.user = new Models.User();
assignment.user.Id = item.t3.Id;
assignment.user.FirstName = item.t3.FirstName;
assignment.user.LastName = item.t3.LastName;
lstassgn.Add(assignment);
}
return lstassgn;
}
AssignedStudents.cshtml
<div class="col-md-12">
<h2>Submitted Assignments</h2>
<table class="table table-bordered table-responsive table-hover" id="tbl">
<tr>
<th>
Name
</th>
<th>
Assignment 1
</th>
</tr>
#foreach (var item in ViewBag.StudentAssignment)
{
bool flag = true;
<tr class="item">
#foreach (var item1 in item.Value)
{
foreach (var item2 in item1.Value)
{
if (flag == true)
{
<td>
#item2.user.FirstName
</td>
flag = false;
}
break;
}
<td>
#foreach (var item2 in item1.Value)
{
<img src="#" />
}
#foreach (var item2 in item1.Value)
{
if (item2.Result != null && item2.Result != "Pending")
{
<div><input type="text" value="#item2.Result" class="txtbox" id=#Guid.NewGuid().ToString() disabled="disabled"/></div>
}
else
{
<div><input type="text" class="txtbox" id=#Guid.NewGuid().ToString() /></div>
}
<input type="hidden" id="stdassgnid" value="#item2.Id" />
break;
}
</td>
}
</tr>
}
</table>
<input type="button" id="saveResult" value="Save Result" class="btn btn-success" />
</div>
Edited:-
Since I've managed to pass the results in the required textboxes. I'm here surrounded by another issue which is the next assignment submission. The first column contains the submitted marks already, and this time instructor would carry out the marking of the next assignment. Therefore, The system would look for the next column as the previous column already contains marks.
$("#saveResult").click(function () {
$("#tbl tr.item").each(function () {
$(this).find("input.txtbox").attr("disabled", "disabled");
var Mkrs = $(this).find("input.txtbox").val();
var Id = $(this).find("#stdassgnid").val();
alert(Mkrs)
$.ajax({
type: "POST",
url: '#Url.Action("UpdateResult", "Assignment")',
data: { Marks: Mkrs, studentAssgnId: Id},
dataType: "json",
success: function (data) {
if(data.message!=null)
{
alert(data.message)
}
}
})
});
I am trying to add a simple checkbox feature to each day in my calendar view. It must be inline with the style of the current calendar and when a bool is selected it must be able to save the changes to the database. Any suggestions would be appreciated.
My main issue at the moment is the checkboxes that are being selected are not being saved to the db.
Controller.cs
private F2FW _db = new F2FW();
[HttpGet]
public ActionResult CalendarIndex()
{
List<Event> events = new List<Event>();
Project.Models.Calendar calendar = new Project.Models.Calendar();
calendar.SetDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
calendar.View(#"~\Views\Patient\Calendar.cshtml");
calendar.ViewData.Add("events", events);
ViewBag.calendar = calendar.Render();
return View(calendar);
}
[HttpPost]
public ActionResult CalendarIndex(User user, CalendarArg calArg, int dayCounter, string[] cbx_day, Patient patient, SessionExercise sessionExercise)
{
SessionInformation sessiondata = new SessionInformation();
Session lastsession = db.Sessions.Where(s => s.ActiveUserID == user.UserID).OrderByDescending(e => e.StartedAt).FirstOrDefault();
calArg.CompletedToday = DateTime.Today;
if (ModelState.IsValid)
{
if (calArg.CompletionRequested == false)
{
//do nothing!
}
else if (calArg.CompletionRequested == true)
{
if (sessiondata.Completed == true)
{
if (sessionExercise.FinishedAt == calArg.Past)
{
List<Event> events = new List<Event>();
events.Add(new Event() { Title = "Exercises Completed", EventDate = DateTime.Now.AddDays(0), Type = Event.EventType.Vacation }); //green
}
}
if (sessiondata.Completed == false)
{
if (sessionExercise.FinishedAt == calArg.Past)
{
List<Event> events = new List<Event>();
events.Add(new Event() { Title = "Exercises Uncompleted", EventDate = DateTime.Now.AddDays(0), Type = Event.EventType.Critical }); //red
}
}
}
_db.SaveChanges();
return RedirectToAction("CalendarIndex"); // or where ever you want to go
}
else
{
return View(calArg);
}
}
public class Event
{
public string Title
{
get;
set;
}
public DateTime EventDate
{
get;
set;
}
public EventType Type
{
get;
set;
}
public enum EventType
{
Appointment,
Meeting,
Vacation,
Birthday,
Personal,
Critical
}
}
Model.Calendar.cs
public class Calendar
{
int _year;
int _month;
DateTime _selectedDate;
string _viewFile = "";
ViewDataDictionary _viewData = new ViewDataDictionary();
Func<DateTime, bool, string> _onDayRenderFunc = null;
public Calendar()
{
SetDate(DateTime.Now.Year, DateTime.Now.Month);
}
public void SetDate(int year, int month)
{
_year = year;
_month = month;
_selectedDate = new DateTime(_year, _month, 1);
}
public void SetDate(int year, int month, int day)
{
_year = year;
_month = month;
_selectedDate = new DateTime(_year, _month, day);
}
public DateTime Date
{
get
{
return _selectedDate;
}
}
public void OnDayRender(Func<DateTime, bool, string> func)
{
_onDayRenderFunc = func;
}
public void View(string viewFile)
{
_viewFile = viewFile;
}
public ViewDataDictionary ViewData
{
get
{
return _viewData;
}
}
public string Render()
{
string[] dayNames = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int daysInMonth = DateTime.DaysInMonth(_year, _month);
int pYear = _year;
int pMonth = _month;
if ((_month - 1) < 1)
{
--pYear;
pMonth = 12;
}
else
{
--pMonth;
}
int daysInPrevMonth = DateTime.DaysInMonth(pYear, pMonth);
DateTime d1 = new DateTime(_year, _month, 1);
int dayPos = (int)d1.DayOfWeek;
daysInPrevMonth -= dayPos - 1;
StringBuilder control = new StringBuilder();
control.Append("<table cellpadding=\"0\" cellspacing=\"0\">\n<thead>\n<tr>\n");
for (int i = 0; i < dayNames.Length; i++)
{
control.Append(string.Format("<th>{0}</th>\n", dayNames[i]));
}
control.Append("</thead>\n<tbody>\n");
int totalDaysInMonth = daysInMonth + dayPos;
int col = 0;
int day = 0;
string cellValue = "";
for (int idx = 0; idx < totalDaysInMonth; idx++)
{
if (col == 0)
{
control.Append("<tr>\n");
}
if (idx >= dayPos)
{
++day;
if (_viewFile == "")
{
cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(_year, _month, day), true) : day.ToString();
}
else
{
ViewData.Model = new CalendarArg() { Date = new DateTime(_year, _month, day), SelectedDate = _selectedDate, CurrentMonth = true };
cellValue = this.Parse(_viewFile);
}
control.Append(string.Format("<td data-day=\"{0}\" data-month=\"{1}\" data-year=\"{2}\">{3}</td>\n", day, _month, _year, cellValue));
}
else
{
if (_viewFile == "")
{
cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(pYear, pMonth, daysInPrevMonth), false) : daysInPrevMonth.ToString();
}
else
{
ViewData.Model = new CalendarArg() { Date = new DateTime(pYear, pMonth, daysInPrevMonth), SelectedDate = _selectedDate, CurrentMonth = false };
cellValue = this.Parse(_viewFile);
}
control.Append(string.Format("<td>{0}</td>\n", cellValue));
++daysInPrevMonth;
}
if (col == 6)
{
control.Append("</tr>\n");
col = 0;
continue;
}
++col;
}
if (col < 7)
{
int nextMonthDay = 1;
for (int c = col; c < 7; c++)
{
if ((_month + 1) > 12)
{
++_year;
_month = 1;
}
else
{
++_month;
}
if (_viewFile == "")
{
cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(_year, _month, nextMonthDay), false) : nextMonthDay.ToString();
}
else
{
ViewData.Model = new CalendarArg() { Date = new DateTime(_year, _month, nextMonthDay), SelectedDate = _selectedDate, CurrentMonth = false };
cellValue = this.Parse(_viewFile);
}
control.Append(string.Format("<td>{0}</td>\n", cellValue));
++nextMonthDay;
}
control.Append("</tr>\n");
}
control.Append("</tbody>\n</table>\n");
return control.ToString();
}
private string Parse(string viewFile)
{
using (var sw = new StringWriter())
{
ControllerContext ctx = new System.Web.Mvc.ControllerContext();
ctx.HttpContext = new HttpContextWrapper(HttpContext.Current);
RazorView view = new RazorView(ctx, viewFile, "", false, null);
TempDataDictionary tdd = new TempDataDictionary();
var viewContext = new ViewContext(ctx, view, ViewData, tdd, sw);
view.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
Model.CalendarArg.cs
public class CalendarArg
{
public DateTime SelectedDate { get; set; }
public DateTime Date { get; set; }
public bool CurrentMonth { get; set; }
public bool CompletionRequested { get; set; }
public DateTime CompletedToday { get; set; }
}
View.CalendarIndex.cshtml
<style>
table {
width: 100%;
border: 0px;
border-collapse: collapse;
border: 1px solid #EEE;
}
table thead tr th {
font-family: Tahoma;
font-weight: normal;
color: #666;
}
table tbody tr td {
border: 1px solid #EEE;
width: 14%;
}
table tbody tr td .cell1, .cell2 {
min-height: 150px;
height: 100%;
}
table tbody tr td .selected_day h2 {
Color: #FFF;
background-color: #3498DB;
text-shadow: none;
}
table tbody tr td .cell1 {
background-color: #FFF;
}
table tbody tr td .cell1:hover h2 {
box-shadow: 1px 2px 3px #999;
}
table tbody tr td .cell2 {
background-color: #FCFCFC;
}
table tbody tr td .cell2 h2 {
color: #CCC;
}
table tbody tr td h2 {
font-family: Tahoma;
font-size: 20px;
font-weight: normal;
float: right;
margin: 0px;
padding: 6px;
color: #154B67;
background-color: #EEE;
display: block;
width: 25px;
height: 25px;
text-align: center;
text-shadow: 2px 1px #FFF;
}
table tbody tr td .evt {
font-family: Tahoma;
font-size: 12px;
margin: 5px;
padding: 10px;
color: #FFF;
border-radius: 2px;
}
table tbody tr td .clear {
clear: both;
}
.Meeting {
background-color: #DDD;
color: #222 !important;
}
.Personal {
background-color: #3498DB;
}
.Vacation {
background-color: #2ECC71;
}
.Appointment {
background-color: #F5AB35;
}
.Critical {
background-color: #F22613;
}
</style>#Html.Raw(ViewBag.calendar)
View.Calendar.cshtml
#model Project.Models.CalendarArg
#{
CalendarArg calArg = this.Model;
List<Project.Controllers.Event> events = (List<Project.Controllers.Event>)ViewData["events"];
string cssClass = calArg.CurrentMonth == true ? "cell1" : "cell2";
}
#if (calArg.Date.Day == calArg.SelectedDate.Day)
{
cssClass += " selected_day";
}
#if (calArg.Date.Day == calArg.Date.Day)
{
if (DateTime.Now <= calArg.Date)
{
#Html.CheckBoxFor(m => m.CompletionRequested, new { #checked = calArg.CompletionRequested });
}
}
<div class="#cssClass">
<h2>#calArg.Date.Day.ToString()</h2>
<div class="clear"></div>
#foreach (var evt in events)
{
if (evt.EventDate.Date.ToString("yyyyMMdd") == calArg.Date.ToString("yyyyMMdd"))
{
<div class="evt #evt.Type.ToString()">#evt.Title</div>
}
}
</div>
UPDATE
By adding this line of code to Calendar.cshtl:
#if (calArg.Date.Day == calArg.Date.Day)
{
#Html.CheckBoxFor(m => m.CompletionRequested, new { #checked = calArg.CompletionRequested });
}
It surprisingly works, so i guess i'd like to know how to alter the css style sheet in calendar index to have the checkboxes flush with the calendar design (i.e. inline with the calendar and not just above it) and how to save changes to the bool to the db.
Have this inside the foreach loop:
#Html.CheckBoxFor(m => m.CompletionRequested , new { #checked = evt.CompletionRequested });
UPDATE:
Answer to your question in comments. Do HttpPost to controller and pass model data.
[HttpPost]
public ActionResult CalendarIndex(CalendarArg model)
{
// Check that model is valid
if(ModelState.IsValid)
{
// CODE here to update Database
return RedirectToAction("Index"); // or where ever you want to go
}
else
{
return View(model); // Return back to View, model is not valid
}
}
UPDATE 2:
If you want to add a class name you can do it like this:
#Html.CheckBoxFor(m => m.CompletionRequested , new { #checked = evt.CompletionRequested, #class = "checkbox" });
Or you can add css like this:
input[type="radio"]:checked
{
// css when radio button is selected
}
input[type="radio"]
{
// css when radio button is not selected
}
These CSS styles is global so every input element with type radio will get styles.
And when you want to change changes to db context, you need first find the current one from context. Then add true value to CompletionRequested property and then call SaveChanged method from your context. You'r first question was to get checkboxes on your calendarView, not how to save changes to db. That's another question.
How can I convert a string to be used as a variable? I have a List of strings that I want to be able to loop through and call data from my Model.
My code:
Controller:
List<string> reportContentsCharts = new List<string>();
//Pseudo Code
//If chart is selected added it to reportContents. So in the view instead of calling #Model.getChart1 from the view I can reference this reportContents.
//For Example:If chart1 and chart2 are selected
reportContentsCharts.Add("getChart1");
reportContentsCharts.Add("getChart2");
IndexViewModel viewModel = new IndexViewModel()
{
chart1 = makeChart1(DictionaryofData), //Returns an image and sends to IndexViewModel
chart2 = makeChart2(DictionaryofData),
chart3 = makeChart2(DictionaryofData),
chart4 = makeChart2(DictionaryofData),
chart5 = makeChart2(DictionaryofData),
chart6 = makeChart2(DictionaryofData),
reportContentsCharts = reportContentsCharts
}
private byte[] makeChart1(Dictionary<string, Double> DictionaryofData)
{
//code to construct chart and return as an image.
}
IndexViewModel:
public Byte[] chart1 { get; set; }
public Byte[] chart2 { get; set; }
public Byte[] chart3 { get; set; }
public Byte[] chart4 { get; set; }
public Byte[] chart5 { get; set; }
public Byte[] chart6 { get; set; }
//This code is repeated for all 6 charts
public string getChart1
{
get
{
string mimeType = "image/png";
string base64 = Convert.ToBase64String(chart1);
return string.Format("data: {0}; base64, {1}", mimeType, base64);
}
}
View:
<table>
for(int z = 0; z< Model.reportContentsCharts.Count / 2 ;z++) //At most 2 charts can be selected
{
<tr>
<td ="center">
<img src=#Model.reportContentsCharts[z]/>
</td>
<td ="center">
<img src=#Model.reportContentsCharts[z+1] />
</td>
</tr>
}
</table>
Under lying issue:
Currently when I run this code it returns me a broken image. I am thinking this might be a syntax issue? I have a handful of graphs that can be displayed on my webpage. Based on input from the user only a select few of the graphs will be displayed. The first thing I did was hard coded a position in the html for each graph and then use if() statements to determine whether to display the graph. The problem with this is that, based on the user input, the selected graphs can appear on separate lines. This creates bad alignment and spacing issues.
I understand that this might not be the best way to do this, but I felt like that it was the simplest solution.
Thanks for any suggestions or help.
It looks to me like the root of the problem is your poorly designed ViewModel. You need to normalize it:
private Dictionary<string, byte[]> Charts = new Dictionary<string, byte[]>();
public string GetChart(string name)
{
get
{
string mimeType = "image/png";
string base64 = Convert.ToBase64String(Charts[name]);
return string.Format("data: {0}; base64, {1}", mimeType, base64);
}
}
public string AddChart(string name, byte[] data)
{
Charts[name] = data;
}
Then you can write your controller something like this:
IndexViewModel viewModel = new IndexViewModel()
{
reportContentsCharts = reportContentsCharts
}
for (int i = 0; i < 6; i++)
{
viewModel.AddChart("chart" + i, makeChart("chart" + i, DictionaryOfData));
}
And finally, you can write your view like this:
<table>
for (int z = 0; z < Model.reportContentsCharts.Count; z += 2)
{
<tr>
for (int c = z; c < z + 2; c++)
{
<td align="center">
if (c < Model.reportContentsCharts.Count)
{
<img src="#Model.GetChart(Model.reportContentsCharts[c])"/>
}
</td>
}
</tr>
}
</table>