Razor View IF to a partial div - asp.net-mvc

The thing is that Im trying to change background color of a div depending on an IF condition inside a foreach and I didnt wanted to make an entire replication of the code for every single condition(3 conditions actually).
My idea was to do something like:
#foreach (var item in Model.Models)
{
#if (item.Status == "COMPLETED")
{
<div class="card teal darken-2 white-text">
}
#if (item.Status == "NOT STARTED")
{
<div class="card grey white-text">
}
#if (item.Status == "RUNNING")
{
<div class="card blue white-text">
}
<div class="card content">
</div>
</div>
</div>
}
But it seems that HTML detects the 3 divs with no closure and it crushes saying that the foreach needs an ending }.
Any ideas?

Your current code is failing because you are trying to mix C# code with plain text.
The if condition opens a C# code block. So if you want to mix plain text or html inside that, you need to use #: prefix. #: tells razor that the following is not C# code, but plain text. It is same as <text></text> tag
You also had an extra closing div.
This should work.
#foreach (var item in Model.SomeCollection)
{
if (item.Status == "COMPLETED")
{
#:div class="card teal darken-2 white-text">
}
if (item.Status == "RUNNING")
{
#:div class="card grey white-text">
}
<div class="card content">#item.Name</div>
#:</div>
}
I personally prefer to add less C# code inside views. I like to keep my views more Htmly. I would create a separate method which can return the css class you need based on the Status value.
Here is an extension method.
public static class UiExtensionMethods
{
public static IHtmlString GetStatusClass(this string item)
{
switch (item)
{
case "COMPLETED":
return MvcHtmlString.Create("teal darken-2 white-text");
case "RUNNING":
return MvcHtmlString.Create("blue white-text");
default:
return MvcHtmlString.Create("gray white-text");
}
}
}
Now all you have to do is, call this method in your view.
<div>
#foreach (var item in Model.Tags)
{
<div class="card #item.Status.GetStatusClass()">
<div class="card content">
#item.Status
</div>
</div>
}
</div>
I created the extension method on string. You can create it on more specific type (Your Status class/Status type(enum?)/ The type of each item in your collection.)

Related

How to change the html tag data with if condition in MVC

I want to change the machine name based on the IMEI number, getting an error while writing if condition inside the div.
<div class="pull-right">
<small>(Imei : #item.DeviceImei)</small>
</div>
<div class="pull-right">
#if (item.DeviceImei==="868997035786332")
{
<small>(Machine : Power Complex)</small>
}
else
{
<small>(Machine:NA)</small>
}
</div>
it's because of your if. When you use an HTML tag, the Razor view engine will be off and you should use # for your next C# code, in this situation, you should use this:
<div class="pull-right">
<small>(Imei : #item.DeviceImei)</small>
</div>
<div class="pull-right">
#if (item.DeviceImei==="868997035786332")
{
<small>(Machine : Power Complex)</small>
}
#else
{
<small>(Machine:NA)</small>
}
</div>

How do I to change the style of a tag using Razor?

I have a HTML tag which I want to only be visible when a condition is true, otherwise it will be hidden. To do this, I'm trying to change the style attribute using Razor, but still can't do this.
Note that: I don't want to use JQuery, I want to use only Razor.
How could I do this ?
Trying
<!--it will only visible if the conditional true-->
<div class="form-group" #(usuario.role == RoleType.Investidor) ? style="display:none;" : style="display:normal;">
<h1>Description</h1>
</div>
I would assume something like this works:
<div class="form-group" style="#(usuario.role == RoleType.Investidor ? "display: none" : string.Empty)">
<h1>Description</h1>
</div>
Move the ternary statement inside the attribute value for style. You may also be able to replace string.Empty with null - depending on context, that might enable the Razor engine to omit the attribute, rather than rendering an empty value.
You could try to do something like that:
#if (usuario.role != RoleType.Investidor)
{
<div class="form-group" style="display: normal">
<h1>Description</h1>
</div>
}
If RoleType equals Investidor, the div will not be shown at all.
If presence of this element is important to you, you can leave it like that:
#if (usuario.role != RoleType.Investidor)
{
<div class="form-group" style="display: normal">
<h1>Description</h1>
</div>
} else {
<div class="form-group" style="display: none">
<h1>Description</h1>
</div>
}

Ajax.BeginForm works first time, but calls method twice from second call

Ajax.BeginForm works first time, but calls method twice from second call.. I have referenced all the required scripts.
Firstly, In my main view, I have a common div for two partail views and I am loading respective views based on a radio button selection.
My Select Partial View
<div>
#using (Ajax.BeginForm("GetRandomThirdPartyList", "RandomList", new AjaxOptions { UpdateTargetId = "Contractors" }, new { id = "FORM" }))
{
<div id="Contractors">
<div id="ThirdParty">
<br />
<h3>Third Party Contractors</h3><hr />
<div>Enter High Risk Percentage: #(Html.Kendo().TextBoxFor<int?>(model => model.HighThirdPercent)
.HtmlAttributes(new { style = "width: 50px; height:25px" })
)
</div>
<input type="submit" value="Generate Report" class="k-button btn-primary" id="btn_thirdpaty" />
#* <b>#Html.DisplayFor(model => model.TotHighRisk) HighRisk Employees / #(Html.DisplayFor(model => model.TotLowRisk)) LowRisk Employees</b>*#
</div>
<br />
<div id="ThirdPartytab">
<div id="ReportForm" class="k-content">
<ul id="tabstrip2" class="nav nav-tabs" role="tablist">
<li class="active">HighRisk Third Party Contractors</li>
#* <li style="float:right"><img src="~/Images/icon_ssrs.png" title="Export to SSRS" /></li>*#
</ul>
#*Tab Content Containers*#
<div class="tab-content">
#if (Model.ThirdParty != null)
{
<div class="tab-pane fade in active" id="ThirdPartytab"> #Html.Partial("ThirdParty", Model) </div>
}
</div>
</div>
</div>
</div>
}
My Controller :
int tphigh = 0;
// GET: /RandomList/
[HttpPost]
public ActionResult GetRandomThirdPartyList(VM.RandomList random)
{
// tphigh=Convert.ToInt32(random.HighThirdPercent);
if (random.HighThirdPercent != null)
{
tphigh = Convert.ToInt32(random.HighThirdPercent);
// RedirectToAction("HighRiskCOPL", high);
}
List<VM.RiskList> risklist = (List<VM.RiskList>)AutoMapDomainModel<List<VM.RiskList>>(randomDBentity.GetRandomList(0, 0, tphigh,null));
mainlist.HighThirdPercent = tphigh;
mainlist.ThirdParty = //some list as third party is a Ienumerable
return PartialView("ThirdPartyContractors",mainlist);
}
The form posts properly first time, but from second time, it calls all the code lines in the action method tiwce, sometimes in a haphazard order and finally either populates the grid, or doesnt send any result.
Solved it.. My updatetargetid div was not the parent div..
replaced that..

Razor parse error- nested if and html within a foreach loop

I'm trying to execute the following code in asp.net razor view-
#foreach (var contact in ViewBag.ContactInfo.Rows)
{
if (columnCount>4)
{
<div class="row-fluid">
}
<div class="span4">#ViewBag.SomeText</div>
//This if block is treated as normal text.
if (columnCount > 4)
{
</div>
columnCount = 0;
}
columnCount++;
}
But it gives parse error.
Any help?
Try something like below. As you are opening div tag in one if and closing in other, razor viewengine is somehow not able to parse it. Check here for more
#foreach (var contact in ViewBag.ContactInfo.Rows)
{
if (columnCount>4)
{
<div class="row-fluid">
<div class="span4">#ViewBag.SomeText</div>
</div>
}
else
{
<div class="span4">#ViewBag.SomeText</div>
}
columnCount++;
}
#foreach (var contact in ViewBag.ContactInfo.Rows)
{
if (columnCount>4)
{
#:<div class="row-fluid">
}
<div class="span4">#ViewBag.SomeText</div>
//This if block is treated as normal text.
if (columnCount > 4)
{
#:</div>
columnCount = 0;
}
columnCount++;
}

Using if has value statement in razor view not working

I have a db table with 3 different {price (value> int)} parameters
I would like in my view that in case one of them has value in it to display same html code
I had tried something like this in my view (not working)
#if(item.price_e.HasValue )
<text> €
}
#if(item.price_d.HasValue)
<text>$
}
else
item.price
what the way to do it?
My view
#foreach (var item in Model) {
<div class="prod" >
<div class="prodh">
<h3> #item.destination
#item.City
#item.pkg_type
</h3>
#item.description
//i have also tryed this Not working
#if(item.price !=0)
{
<text>bla
}
#if(item.price_d !=0)
{
<text>$
}
</div>
<div class="prodb">
#item.date
#item.company.company_id
#item.destination</div>
</div>
}
You are missing some } and haven't closed the <text> with </text>
#if(item.price_e.HasValue ) {
<text> €</text>
}
#if(item.price_d.HasValue) {
<text>$</text>
}
else {
#item.price
}
Your second code sample is also missing a </div>

Resources