How to Display Conditional Plain Text with Razor - asp.net-mvc-3

I am having issues with displaying (rather NOT displaying) plain text in an else block.
if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
<h3>Careerfields Listing</h3>
<table>
<tr>
<th></th>
<th>Careerfield Name</th>
</tr>
#foreach (var item in Model.CareerFields)
{
<tr>
<td>
#Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
</td>
<td>
#item.CareerFieldName
</td>
</tr>
}
</table>
}
else
{
No Careerfields associated with #ViewBag.SelectedDivisionTitle
}
The if blocks works fine. The text only renders when true. However, the else block text renders when the page loads, not if it evaluates to false only.
I've tried using
Hmtl.Raw("No Careerfields associated with ")
<text>No Careerfields associated with #ViewBag.SelectedDivisionTitle</text>
#:No Careerfields associated with #ViewBag.SelectedDivisionTitle
But it still renders the plaintext before evaluation.
Any suggestions?

Put your "plain text" inside of a naked <span> tag:
else
{
<span>No Careerfields associated with #ViewBag.SelectedDivisionTitle</span>
}
The browser shouldn't render it special (unless you have css selecting every span) and it'll help razor sense the end of the C# and print your HTML.

The following code worked perfectly for me:
#if (false) {
<h3>
Careerfields Listing
</h3>
<table>
<tr>
<th>
</th>
<th>
Careerfield Name
</th>
</tr>
</table>
}
else
{
#:No Careerfields associated with #ViewBag.SelectedDivisionTitle
}
You can see that the contents of if are rendered when you change condition to true.

Looks like you've forgotten the # sign before your if statement. Try this:
#if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
<h3>Careerfields Listing</h3>
<table>
<tr>
<th></th>
<th>Careerfield Name</th>
</tr>
#foreach (var item in Model.CareerFields)
{
<tr>
<td>
#Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
</td>
<td>#item.CareerFieldName</td>
</tr>
}
</table>
}
else
{
<text>No Careerfields associated with #ViewBag.SelectedDivisionTitle</text>
}

The most concise and correct answer is:
Prepend #: before the text.
(note the : after the #)
This still allows to embed variables in the text by prepending an # to the variable name:
#if (someCondition)
{
#:Some text you want to see.
}
else
{
#:Some other text, with a variable #someVariable included in the text.
}

Related

Unable to check checkbox in table cell

I have this table:
<iframe title="ManageLegs">
<table title="Leg Details">
<tr>
<th class="headerRow">
<div>PAX</div>
</th>
<th class="headerRow">
<div>Leg</div>
</th>
</tr>
<tr>
<td>
<input type="text"></input>
</td>
<td>
<input type="checkbox"></input>
</td>
</tr>
</table>
</iframe>
Accessing the textbox is working fine, but I canĀ“t figure out how to check the checkbox.
I use the following code in my PageObject class:
in_iframe(:title => 'ManageLegs') do |frame|
table(:leg_details, title: 'Leg Details', :frame => frame)
text_field(:pax) { leg_details_element['1']['PAX'].text_field_element }
text_field(:aircraft) { leg_details_element['1']['Aircraft'].text_field_element }
text_field(:show_leg_on_quote_pdf) { leg_details_element['1']['Leg'].checkbox_element }
end
Which I am calling like this:
on(CharterInquirySavedPage).pax = "2"
on(CharterInquirySavedPage).check_show_leg_on_quote_pdf
It is working fine for setting the pax-textbox, but fails when trying to check the checkbox:
NoMethodError: undefined method `check_show_leg_on_quote_pdf' for #<CharterInquirySavedPage:0x00000004cfd420>
The text_field accessor is for text fields, which are input elements with type "text" and other text-like input fields such as "email".
Inputs of type "checkbox" are considered checkboxes. It is the checkbox accessor that creates the check_ method. In other words, you want the following definition for the checkbox:
checkbox(:show_leg_on_quote_pdf) { leg_details_element['1']['Leg'].checkbox_element }

MVC 3 Processing a table row depending on whether a check box is checked

Hi I am very new to MVC and I am currently trying to implement a small human resources system using MVC 3 and Entity Framework 4.1. Right now I am stuck on what seems like a very trivial task of displaying a table which lists employees who have recently taken sick leave off from work and on each table row I have a checkbox which users will check if the the employee has provided a sick sheet. I also want to have a button/Link/etc on each row which when clicked would invoke a call to a controller method and somehow pass the checked value of the check box together with the id of the sick leave application. I tried using an actionlink but I'm kind of stumped at what I would enter in as the routevalue meant for the checked value of the checkbox. This same functionality would take me only minutes to do in web forms but like I said I'm new to MVC and since this seems like a pretty simple task there is probably a pretty simple solution somewhere out there but I just can't figure it out for the life of me. If anything I'm guessing this might need a bit of jquery (which btw still looks like a foreign language to me sometimes) and hidden fields? Arrgghhh I don't know. Could someone please help me?? Thanks in advance.
Here is my View:
#model IEnumerable<LeaveSoft.Models.PendingSickLeave>
<table>
<tr>
<th>
Applicant's Name
</th>
<th>
Leave Start
</th>
<th>
Leave End
</th>
<th>
Number Of Days
</th>
<th>
Reason
</th>
<th>
Confirm
</th>
<th>
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserFullName)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.NumOfDays)
</td>
<td>
#Html.DisplayFor(modelItem => item.LeaveReason)
</td>
<td>
#Html.CheckBox("chkConfirm")
#Html.Label("", "Sick Sheet Provided")
</td>
<td>
#Html.ActionLink("Process", "ProcessSickLeave", new { id = item.ApplicationID, sicksheet = "THIS IS THE PART I DON'T KNOW" })
</td>
</tr>
}
</table>
here's a quick solution off the top of my head (table shortened due to my laziness):
HTML/RAZOR:
<table>
<tr>
<th>ApplicantName</th>
<th>Confirm</th>
<th></th>
</tr>
#foreach (var item in Model.PendingSickLeave) // this is a List<>
{
<tr>
<td>#item.UserFullName</td>
<td>#Html.CheckBoxFor(m => item.SickSheet, new { #id = "chk" + #item.ApplicationID })</td>
<td>#Html.ActionLink("Process", "ProcessSickLeave", new { id = item.ApplicationID }, new { #class="submit", #data_val = item.ApplicationID })</td>
</tr>
}
</table>
JQUERY SCRIPT:
<script>
$(function () {
// captures click event. appends the sicksheet querystring on the url.
$('a.submit').click(function (e) {
e.preventDefault();
var id = $(this).attr('data-val');
var chk = $('#chk' + id);
if ($(chk).is(':checked'))
$(this).attr('href', $(this).attr('href') + '?sicksheet=true');
else
$(this).attr('href', $(this).attr('href') + '?sicksheet=false');
});
});
</script>
Basically, when you click on the Process actionlink, the jquery looks for a checkbox with matching ID, then if it's checked, it puts a ?sicksheet=true at the end of the url before continuing.
edit:
ROUTE:
routes.MapRoute("ProcessSickLeave", "process/processsickleave/{applicationid}",
new { controller = "Process", action = "ProcessSickLeave" });
CONTROLLER:
public ActionResult ProcessSickLeave(ProcessViewModel m)
{
return Content("ID = " + m.ApplicationID +
"<br/> Has Sick sheet: " + m.SickSheet.ToString(), "text/html");
}

Using linq to remove a href tag inside cdata in xml file

I have following xml file:
<ab>
<![CDATA[
<table>
<tbody>
<tr>
<th>abcdef</th>
<th>Contact</th>
</tr>
<tr>
<p>
Home
</p>
</tr>
</tbody>
</table>
]]>
</ab>
I am still learning linq. Want to know if there is an easier way to find all a href = "/1/2/" tags inside cdata and remove them. Like in above example it should just show Contact and Home and remove the
void Main()
{
XDocument doc = XDocument.Load("C:\\test.xml");
XDocument xdoc = XDocument.Parse(doc.ToString());
XNode node = xdoc.DescendantNodes().Single(x => x.NodeType == XmlNodeType.CDATA);
if (node.Parent != null)
{
string content = node.Parent.Value.Trim();
IEnumerable<XElement> elements =
XDocument.Parse(content).Descendants().Where(x =>
{
XAttribute xAttribute = x.Attribute("href");
return
xAttribute !=
null && xAttribute.Value == "/1/2";
});
// do something here
}
}
contents of test.xml is
<ab>
<![CDATA[
<table>
<tbody>
<tr>
<th>abcdef</th>
<th>Contact</th>
</tr>
<tr>
<p>
Home
</p>
</tr>
</tbody>
</table>
]]>
</ab>
I don't think LINQ is the best way to go about this problem. Personally, I would use Regular Expression. Here is an example of how this could be done:
Example: Scanning for HREFs
In general, if you are doing any more intensive HTML processing, using an HTML parser is probably the best way to go, such as HtmlAgilityPack.
Regex sample code:
Regex hrefRegex = new Regex(#"href=""([^""]*"")", RegexOptions.IgnoreCase | RegexOptions.Compiled);
string output = hrefRegex.Replace(input, new MatchEvaluator(m => string.Empty));
Hope this helps,
Ivan

MVC Razor Rendering controls dynamically

This is one way I've found to render controls dynamically with ASP.NET MVC 3 Razor. This is giving me correct data, but I'm curious if anyone sees any red flags with this method, or a painfully more obvious way to do this.
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<tr>
<td>
#item.app_name
</td>
<td>
#item.setting_name
</td>
<td>
#item.setting_description
</td>
<td>
#if (item.data_type == "Bit")
{
#Html.CheckBox("setting_value", item.setting_value == "1" ? true : false)
}
else
{
#Html.TextBox("setting_value", item.setting_value)
}
</td>
<td>
#item.setting_value
</td>
</tr>
}
}
You could use Editor and Display Templates instead...
Check out this link:
http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx
What do editor templates have to do with dynamically creating controls?
What if you need to drive a UI/View from settings in a database, for example?

MVC3 Razor Syntax troubles

I'm trying to make a very simple view using Razor syntax in MVC3, but it seems I can't get the syntax right.
I have a simple table like this
<table>
<tr>
#{
var counter = 0;
}
#foreach (var category in ViewBag.Categories)
{
counter++;
<td>
<input type="checkbox" checked="checked" name="#("category" + category.Code)" />
#category.Description
</td>
if (counter % 2 == 0)
{
</tr>
<tr>
}
}
</tr>
</table>
When I insert the and inside the if-statement, I receive this error
The using block is missing a closing "}" character.
If I try to wrap those two tags inside and , I get this error instead:
The "tr" element was not closed.
Your </tr><tr> messes up the "flow" of the html/code mix.
You are closing the tr-tag on a different level, not a different level in the html, but inside the code. You should trick razor into outputting html, that it does not parse itself.
You could include them like this:
#:</tr><tr>
or
#Html.Raw("</tr><tr>")
The result:
if (counter % 2 == 0)
{
#:</tr><tr>
}
Click for Haack's quick reference of Razor syntax
I would say you're missing the # in front of the if statement. Try #if(counter % 2 == 0).
Hope that helps.
Update
I checked it out and the answer from GvS seems to work just fine. The # is not necessary for the if statement.
#for (int i = 0; i < 5; i++)
{
if (i == 3)
{
#:</tr><tr>
}
}
You are mixing HTML and code in the foreach. That's why you get problems.
Either use <text></text> block around the HTML, or do the following:
<table>
<tr>
#{
var counter = 0;
}
#foreach (var category in ViewBag.Categories)
{
#{
counter++;
}
<td>
<input type="checkbox" checked="checked" name="#("category" + category.Code)" />
#category.Description
</td>
#if (counter % 2 == 0)
{
</tr>
<tr>
}
}
</tr>
</table>

Resources