My site has a column that displays the news. The DIV-s with these news which contain the word "prize" must be painted in the green color. (If a person has created a record (a news) without specifying the Prize (without word "Prize"), the green is not necessary. But if a person filled out the field model.Prize (so in the text we have a word "Prize") the div must be painted in green color.
In a view for creating news there is a field model.Prize
<div class="editor-field">
#Html.TextAreaFor(model => model.Prize,4,55,null)
#Html.ValidationMessageFor(model => model.Prize)
</div>
The value of model.Prize takes the Controller which create a new news record.
public ActionResult Create(Project project)
{
if (ModelState.IsValid)
{(some code...)
News n = new News();
n.Date = DateTime.UtcNow;
n.Description = project.Shortdescription+"\r\n\Prize:\r\n"+project.Prize;
(some code…)
NewsController.Add(db,n);
db.SaveChanges();
return RedirectToAction("Main");
}
In the another method Block of News Controller I display the news:
public PartialViewResult Block()
{
List<News> news = new List<News>();
Int32 count = 0;
foreach (News n in db.News.ToList().OrderByDescending(n => n.Date))
{
if (count++ < 13) news.Add(n);
}
return PartialView(news);
For each entry in the View Block creates <div class ="newsWrapper"> in which the news record insert.
#foreach (var item in Model){
<div class ="newsWrapper">
<p class="newsDate">#item.Date.AddHours(4).ToString("dd.MM.yyyy HH:mm")</p>
#item.Title
<p>#Html.Raw(Html.Encode(item.Description).Replace("\n", "<br />"))</p>
</div>
}
I tried to solve the problem
I added the new div in the Block View:
#foreach (var item in Model)
{
<div class ="newsWrapper">
<div class="#(ViewBag.IsPrize == true ? "GreenNewsClass" : "")">
<p class="newsDate">#item.Date.AddHours(4).ToString("dd.MM.yyyy HH:mm")</p>
#item.Title
<p>#Html.Raw(Html.Encode(item.Description).Replace("\n", "<br />"))</p>
</div>
</div>
}
The GreenNewsClass will paint this div in green color.
But how can I get ViewBag.IsPrize == true if n.Description contains the word Prize,
and ViewBag.IsPrize == false if it's not?
I tried to change the method Block:
public PartialViewResult Block()
{
List<News> news = new List<News>();
Int32 count = 0;
foreach (News n in db.News.ToList().OrderByDescending(n => n.Date))
{
if (count++ < 13) news.Add(n);
if (n.Description.Contains("Призы"))
{
ViewBag.IsPrize = true;
}
else { ViewBag.IsPrize = false; }
}
return PartialView(news);
but it paints all news in green color, not only those which contain the word Prize.
It sounds like you want to do this:
#foreach (var item in Model)
{
<div class ="newsWrapper">
<div class="#(item.Description.Contains("Призы") ? "GreenNewsClass" : "")">
<p class="newsDate">#item.Date.AddHours(4).ToString("dd.MM.yyyy HH:mm")</p>
#item.Title
<p>#Html.Raw(Html.Encode(item.Description).Replace("\n", "<br />"))</p>
</div>
</div>
}
First try to add a property to your model instead to your ViewBag, it seems like you only have a single value in your ViewBag.
Remove the true condition because it's redundant, move the class definition inside the condition that way the div will be empty when the condition is false
and try the following:
#foreach (var item in Model)
{
<div class ="newsWrapper">
<div #(item.IsPrize? "class=GreenNewsClass" : "")>
<p class="newsDate">#item.Date.AddHours(4).ToString("dd.MM.yyyy HH:mm")</p>
#item.Title
<p>#Html.Raw(Html.Encode(item.Description).Replace("\n", "<br />"))</p>
</div>
</div>
}
I have not verified the code but try it out.
Related
I have a dropdownlist in edit view that has a value from the database. What I want to do is to display the saved value in separate dropdown list. For example, I have saved two different data in database with same foreign key to determine that these two records are treated as one. (See below sample image)
https://imgur.com/ex57YTO
I am only using single-selection dropdown list and I am only looping the count of records to determine how many dropdown list to display in the edit page. So if I have "No harm event" and "Complaints" events, this must be displayed in separate dropdown list because what I did now is they are both displaying in one dropdown list so the result is it looks like the record is duplicated (see image below) but actually these two records are in each of the dropdown list.
https://imgur.com/YlVZHWx
https://imgur.com/FXYO4Tn
VIEW
//for loop to count records that will determine how many dropdown list to be displayed
#for (var i = 0; i < Model.SavedEventsToList.Where(a => a.incidentReportId == Model.IRId).Count(); i++)
{
<tr>
<td style="border-bottom:none !important;border-top:none !important;">
<div class="input-group">
<select class="form-control pseEventDDLInEdit" id="pseEventListInEdit" name="pseAddedEvent">
#{
foreach (var item in Model.SavedEventsToList)
{
if (item.selected == "yes")
{
if (item.incidentReportId == Model.IRId) //this is the foreign key that determine these two records are as one
{
<option value=#item.pseEventsId selected>#item.pseEventsName</option>
}
}
else
{
<option value=#item.pseEventsId>#item.pseEventsName</option>
}
}
}
</select>
</div>
</td>
</tr>
}
CONTROLLER
public ActionResult Edit(Guid? id)
{
IMRBusinessLogic imrLogic = new IMRBusinessLogic();
var imrRepo = new IMRRepository();
IMRDTO imr = imrRepo.GetIRDetailsForEdit(id);
imr.SavedEventsToList = imrLogic.SavedEvents(id);
return View(imr);
}
public List<PSESavedEventsDTO> SavedEvents(Guid? incidentReportId)
{
using (IREntities db = new IREntities())
{
var events = (from a in db.SavedPatientSafetyEvents(incidentReportId)
select new PSESavedEventsDTO
{
pseSavedEventId = a.pse_saved_event_category_and_subcategory_id,
pseEventsId = a.pse_events_id,
pseEventsName = a.pse_events_name,
seqNum = a.seq_num,
incidentReportId = a.incident_report_id,
savedRowIndex = a.saved_row_index,
selected = a.selected
}).ToList();
return events;
}
}
I need to separate them so the user can still have an option to edit each of these two records.
This is the expected output I need: https://imgur.com/uwVjvkz
Can someone help me with this.
Thank you in advance.
I already found the solution in this. I just use foreach instead of for loop, and I get the desired output I need.
#foreach (var index in Model.SavedEventsToList.Where(a => a.savedRowIndex != 0))
{
<tr>
<td style="border-bottom:none !important;border-top:none !important;">
<div class="input-group">
<select class="form-control pseEventDDLInEdit" id="pseEventListInEdit" name="pseAddedEvent">
#{
foreach (var item in Model.SavedEventsToList)
{
if (item.selected == "yes")
{
if (item.incidentReportId == Model.IRId && item.savedRowIndex == index.savedRowIndex)
{
<option value=#item.pseEventsId selected>#item.pseEventsName</option>
}
}
else
{
<option value=#item.pseEventsId>#item.pseEventsName</option>
}
}
}
</select>
<span title="Patient Safety Events Description" class="input-group-addon" data-toggle="popover" data-container="body" data-placement="right" data-trigger="hover" data-html="true" href="#" id="login"><i class="fa fa-info-circle"></i></span>
</div>
</td>
</tr>
}
I'm outputting a large list of items on my page using Razor and MVC 5. Here's what I have currently:
#foreach (var item in Model.Items)
{
<a>#item.Name</a>
}
What I'm trying to do is something that would output this:
<div class="tab-0">
<a>Item 1</a>
<a>Item 2</a>
<a>Item 3</a>
<a>Item 4</a>
</div>
<div class="tab-1">
<a>Item 5</a>
<a>Item 6</a>
<a>Item 7</a>
<a>Item 8</a>
</div>
<div class="tab-2">
<a>Item 9</a>
<a>Item 10</a>
<a>Item 11/a>
<a>Item 12</a>
</div>
I need to group every 4 items within a div tag. How can I do that in Razor?
Not sure if your wanting to increment the Item number (or if #item.Name actually contains the incremented number), but the following code will increment both the class name (a new div every 4th iteration) and the item number.
#{ var t = 0; var i = 1; }
<div class="tab-#t">
#foreach (var item in Model.Items)
{
<a>Item #i</a> // this may be just #item.Name?
if (i % 4 == 0)
{
t++;
#:</div><div class="tab-"#t>
}
i++;
}
</div>
Here's my take on the solution. Bear in mind that I haven't compiled the code myself, so please check it:
foreach(var item in Model.Items.Select((x, i) => new {Index = i, Value = x}))
{
if (item.Index % 4 == 0)
{
<div class="tab-#(item.Index/4)">
}
<a>Item #(item.Index + 1)</a>
if (item.Index % 4 == 0)
{
</div>
}
}
// If the number of items has a remainder of 4, close the div tag
if(Model.Items.Count %4 != 0)
{
#:</div>
}
I have added the Value in Linq Select in case you need the information inside the loop.
foreach doesn't give you the index. That's C#.
I suggest you change it to for.
#for (var index = 0; index < Model.Items.Count(); index++)
{
var item = Model.Items[index];
<a>#item.Name</a>
#* Use `item` or `index` as you wish here *#
}
Maybe you'll use Length instead of Count. If Model.Items is just IEnumerable not array or List<>, you might want to call Model.Items.ToList(), etc. You probably get the idea.
In the EditorTemplates, I have a Template which accepts and Model of Type List<string>. This should create an Textbox for each string in the list.
In the Model, the Property has the [UIHint("EditList")]. Now when I render it to the Page, the Template is called correctly, but the index is set wrong. When I submit the form I get:
MyList.[0]:test123
Instead of
MyList[0]:test123
I'm using MVC 3!, the same code workd in my test project which uses MVC 5
View:
<div class="col-md-10">
#Html.EditorFor(model => model.MyList)
#Html.ValidationMessageFor(model => model.MyList)
</div>
Model:
public class FormTest
{
[UIHint("EditListWithAddButton")]
public List<string> MyList { get; set; }
}
EditorForTemplate:
#model List<string>
<div class="EditListWithAddButton">
<ul>
#for (int i = 0; i < Model.Count(); i++)
{
<li>#Html.EditorFor(model => Model[i])</li>
}
</ul>
</div>
Brute force solution but, don't have the time to debug it any futher...
#Html.Raw(#Html.EditorFor(model => Model[i])
.ToString().Replace("__", "_").Replace(".[", "["))
this replaces the Editfortempalt in away, that the index is correct again...
If anybody has a better solution / can explain the problem please tell me
I am using MVC + EF
I have a Feed xml file url that gets updated every 7 minute with items, every time a new item gets added I retrieve all the items to a list variable and then I add these varible to my database table. After that I fill a new list variable which is my ViewModel from the database table. Then I declare the ViewModel inside my view which is a .cshtml file and loop throught all of the objects and display them.
How can I make sure that the newest items get placed on the top and not in the bottom and also the numbers displays in correct order?
This is how I display the items inside my cshtml note that I use a ++number so the newest item needs to be 1 and so on ::
#model Project.Viewmodel.ItemViewModel
#{
int number = 0;
}
<div id="news-container">
#foreach (var item in Model.NewsList.OrderByDescending(n => n.PubDate))
{
<div class="grid">
<div class="number">
<p class="number-data">#(++number)</p>
</div>
<p class="news-title">#(item.Title)</p>
<div class="item-content">
<div class="imgholder">
<img src="#item.Imageurl" />
<p class="news-description">
#(item.Description)
<br />#(item.PubDate) |
Source
</p>
</div>
</div>
</div>
}
</div>
This is how I fill the viewmodel which I use inside the .cshtml file to iterate throught and display the items
private void FillProductToModel(ItemViewModel model, News news)
{
var productViewModel = new NewsViewModel
{
Description = news.Description,
NewsId = news.Id,
Title = news.Title,
link = news.Link,
Imageurl = news.Image,
PubDate = news.Date,
};
model.NewsList.Add(productViewModel);
}
If you check this image thats how it gets displayed with the numbers, thats incorrect.
If you see the arrows thats how it should be, how can I accomplish that?
Any kind of help is appreciated :)
note: When I remove .OrderByDescending, the numbers are correctly on each grid. But I need the .OrderByDescending beacuse i want the latest added item in the top.
Try this:
#model Project.Viewmodel.ItemViewModel
#{
int number = 0;
var NewsItems=Model.NewsList.OrderByDescending(n => n.PubDate).ToList();
}
<div id="news-container">
#foreach (var item in NewsItems)
{
<div class="grid">
<div class="number">
<p class="number-data">#(++number)</p>
</div>
<p class="news-title">#(item.Title)</p>
<div class="item-content">
<div class="imgholder">
<img src="#item.Imageurl" />
<p class="news-description">
#(item.Description)
<br />#(item.PubDate) |
Source
</p>
</div>
</div>
</div>
}
</div>
Looking at your sketch I assume you have float: left or display: inline-block for a grid class. Adding float: right might do the trick.
If that does not help please post CSS you have.
just a quick word..
you are passing NewsViewModel to the view and performing iteration on ItemViewModel ..y?
do u think this may be the cause of the problem..
Regards
You could sort your news list using the CompareTo method:
model.NewsList.Sort((a, b) => b.PubDate.Date.CompareTo(a.PubDate.Date));
Once you have the list sorted correctly, you can simply use CSS to display the news list two items per row. See this fiddle.
The fiddle is a revised one which was provided to me in a similar question I asked before.
Try this one
private void FillProductToModel(ItemViewModel model, News news)
{
var newList = list.OrderByDescending(x => x.News.Date).toList();
var productViewModel = new NewsViewModel
{
Description = newList .Description,
NewsId = newList .Id,
Title = newList .Title,
link = newList .Link,
Imageurl = newList .Image,
PubDate = newList .Date,
};
model.NewsList.Add(productViewModel);
I am trying to display selected skills in my create page. I have the database, I given the connection from the model but i am getting all the skills but when I was selected the skills those are not saving dont know what the problem Can anyone help me? View code is
<div class="editor-field">
#{
IEnumerable<SelectListItem> skill = ViewBag.skill;
foreach (var item in skill)
{
#Html.CheckBox("Skills", false, new { value = item.Value });
<input type="checkbox" name="skillsId" value="#item.Text" />
<label>#item.Text</label>
#Html.ValidationMessageFor(model => model.Skills)
}
}
</div>
and controller code is
int SId = Convert.ToInt32(emp.Skills);
var Sname = (from sn in db.TblSkills
where sn.SkillsId == SId
select sn.Skills).SingleOrDefault();
You can try this code. It is helpful to you.
<%: Html.CheckBox("Skills", Model.Skills.HasValue ? Model.Skills.Value : false)%> Skills