Char equals to String - asp.net-mvc

I am trying to check if a value from database table is equal to Char, in the view I tried
the following:
<% if (Model.MethodOfPayment.ToString().Equals("W") == true)
{
%>
Wire
<%} %>
<%else
{ %>
<% if (Model.MethodOfPayment.ToString().Equals("C") == true)
{
%>
Cheque
<%} %>
<%} %>
Did not work!
In the controller to send the output to PDF Form: I tried the following:
string MyString = order.MethodOfPayment.ToString();
if (MyString == "W")
{
pdfFormFields.SetField("MethodOfPayment", "W");
}
else
{
if (MyString == "W")
{
pdfFormFields.SetField("MethodOfPayment", "C");
}
}
Did not work either.
Thanks in advance.

How about:
if (Model.MethodOfPayment == 'W')
If this doesn't work it simply means that the MethodOfPayment property doesn't equal to the W character. Try debugging your code to see exactly to which value it equals.

Related

Using DomainClassPropertyComparator in grails

In my grails view the ordering applied on the domain class constraints are not picked when i use f:display with each individual property. I heard that domain class property comparator can be used to order the property display as per the constraints applied on the domain class.
Can some body help me on how to use DomainClassPropertyComparator to sort properties on my view?
You can install the scaffolding templates, edit _form.gsp and change the comparator it is using to DomainClassPropertyComparator e.g. my _form.gsp
<%=packageName%>
<% import grails.persistence.Event %>
<% import org.codehaus.groovy.grails.scaffolding.DomainClassPropertyComparator %>
<% excludedProps = Event.allEvents.toList() << 'version' << 'dateCreated' << 'lastUpdated'
persistentPropNames = domainClass.persistentProperties*.name
boolean hasHibernate = pluginManager?.hasGrailsPlugin('hibernate')
if (hasHibernate && org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder.getMapping(domainClass)?.identity?.generator == 'assigned') {
persistentPropNames << domainClass.identifier.name
}
DomainClassPropertyComparator mattsComparator = new DomainClassPropertyComparator(domainClass)
comparator = mattsComparator
props = domainClass.properties.findAll { persistentPropNames.contains(it.name) && !excludedProps.contains(it.name) }
Collections.sort(props, comparator)
for (p in props) {
if (p.embedded) {
def embeddedPropNames = p.component.persistentProperties*.name
def embeddedProps = p.component.properties.findAll { embeddedPropNames.contains(it.name) && !excludedProps.contains(it.name) }
Collections.sort(embeddedProps, comparator)
%><fieldset class="embedded"><legend><g:message code="${domainClass.propertyName}.${p.name}.label" default="${p.naturalName}" /></legend><%
for (ep in p.component.properties) {
renderFieldForProperty(ep, p.component, "${p.name}.")
}
%></fieldset><%
} else {
renderFieldForProperty(p, domainClass)
}
}
private renderFieldForProperty(p, owningClass, prefix = "") {
boolean hasHibernate = pluginManager?.hasGrailsPlugin('hibernate')
boolean display = true
boolean required = false
if (hasHibernate) {
cp = owningClass.constrainedProperties[p.name]
display = (cp ? cp.display : true)
required = (cp ? !(cp.propertyType in [boolean, Boolean]) && !cp.nullable && (cp.propertyType != String || !cp.blank) : false)
}
if (display) { %>
<div class="fieldcontain \${hasErrors(bean: ${propertyName}, field: '${prefix}${p.name}', 'error')} ${required ? 'required' : ''}">
<label for="${prefix}${p.name}">
<g:message code="${domainClass.propertyName}.${prefix}${p.name}.label" default="${p.naturalName}" />
<% if (required) { %><span class="required-indicator">*</span><% } %>
</label>
${renderEditor(p)}
</div>
<% } } %>

How do I manipulate model data in the background for a data visualization in a view?

I'm currently using Rails with D3.js to create a data visualization using model data. What I've done in the view is to extract the model data, aggregate it into categories, and set it as an array of hashes that D3.js can read.
However, I think this slows down page load and I'd like to bring this logic into the background somehow while maintaining instant syncing between model data and the graph (which means when someone updates the model data, the visualization automatically updates itself). Is there a way to do it that gels with the Rails framework?
Ultimately, my goal is really to speed up page load for scale as in the future the dataset will get larger. So any alternative suggestions are welcome.
This is the code pertaining to the data manipulation:
<% #startup_fundings.each do |startup_funding| %>
<% if startup_funding.startup %>
// check if startup belongs to Southeast Asia
<% if countries.any? { |country| startup_funding.startup.locations.include?(country) } == true && startup_funding.amount != nil %>
// split string by individual keywords
<% funding_round_split = [] %>
<% funding_round_split = startup_funding.startup.product_markets.split(", ") if startup_funding.startup.product_markets %>
// check if vertical exists in funding round
<% funding_round_split.each do |funding_round| %>
<% [ ['Hr', 'HR'], ['Bi', 'BI'], ["Crm", "CRM"], ["Lbs", "LBS"], ["Saas", "SaaS"]].each do |replacement|
funding_round.gsub!(replacement[0], replacement[1])
end %>
var fundingRound = "<%= funding_round %>";
var exists = false;
for (i = 0; i < graphData.length; i++) {
if (graphData[i].vertical == fundingRound) {
exists = true;
var order = i;
}
}
// if vertical does not exist, add new vertical
if (exists == false) {
graphData.push({'vertical': fundingRound,
'amount': <%= startup_funding.amount %>,
'deals': [{'company': '<%= startup_funding.startup.company_name %>',
'url': '<%= startup_funding.startup.company_name.downcase.delete(' ').gsub('.', '-') %>',
'amount': <%= startup_funding.amount %>}]
});
} else {
// if vertical exists, add up funding amount
graphData[order].amount = graphData[order].amount + <%= startup_funding.amount %>;
var duplicateRound = false;
// cycle through all funding rounds in a vertical
for (j = 0; j < graphData[order].deals.length; j++) {
// if company in funding round matches iterative company name, indicate it exists
if (graphData[order].deals[j].company == '<%= startup_funding.startup.company_name %>') {
duplicateRound = true;
var order1 = j;
}
}
if (duplicateRound == false) {
graphData[order].deals.push({
'company': '<%= startup_funding.startup.company_name %>',
'url': '<%= startup_funding.startup.company_name.downcase.delete(' ').gsub('.', '-') %>',
'amount': <%= startup_funding.amount %>
});
} else {
graphData[order].deals[order1].amount = graphData[order].deals[order1].amount + <%= startup_funding.amount %>;
}
}
<% end %>
<% end %>
<% end %>
<% end %>

Loop through data, store as array in Ruby on Rails

This is a very beginner question, but I've searched and can't find anything. I'm attempting to loop through an object, then store the information in an array (or object?) so that I can spit out a string of the items.
<% #da = [] %>
<% #report.data_items.each do |di| %>
<% if di.status == "Complete" %>
<% #da += di.url_metric.da %> #not sure how to append to the end of the array
<% end %>
<% end %>
Help? Should I use an array or object?
Seems that you're doing this in ERB template for some reason. Don't. Keep templates clear and simple. Do this kind of calculations in controller.
Here's a better version:
#da = #report.data_items.select {|di| di.status == 'Complete'}.
map{|di| di.url_metric.da }
#da = #report.data_items.collect{|di| di.url_metric.da if di.status == "Complete"}.compact
Here's shorted varian of what you're trying to accomplish:
#da = #report.data_items.select do |item|
item.status == "Complete"
end.map { |item| item.url_metric.da }.join(", ")

How do I construct an if statement within a MVC View

Hopefully this question is quick and painless
I have a mvc view where i want to display either one of two values depending on an if statement. This is what I have in the view itself:
<%if (model.CountryId == model.CountryId) %>
<%= Html.Encode(model.LocalComment)%>
<%= Html.Encode(model.IntComment)%>
If true display model.LocalComment, if false display model.IntComment.
This doesn't work as I get both values showing. What am I doing wrong?
Your if statement always evaluates to true. You are testing whether model.CountryId equals model.CountryId which is always true: if (model.CountryId == model.CountryId). Also you are missing an else statement. It should be like this:
<%if (model.CountryId == 1) { %>
<%= Html.Encode(model.LocalComment) %>
<% } else if (model.CountryId == 2) { %>
<%= Html.Encode(model.IntComment) %>
<% } %>
Obviously you need to replace 1 and 2 with the proper values.
Personally I would write an HTML helper for this task to avoid the tag soup in the views:
public static MvcHtmlString Comment(this HtmlHelper<YourModelType> htmlHelper)
{
var model = htmlHelper.ViewData.Model;
if (model.CountryId == 1)
{
return MvcHtmlString.Create(model.LocalComment);
}
else if (model.CountryId == 2)
{
return MvcHtmlString.Create(model.IntComment);
}
return MvcHtmlString.Empty;
}
And then in your view simply:
<%= Html.Comment() %>
Aside from Darin's point about the condition always being true, you might want to consider using the conditional operator:
<%= Html.Encode(model.CountryId == 1 ? model.LocalComment : model.IntComment) %>
(Adjust for whatever your real condition would be, of course.)
Personally I find this easier to read than the big mixture of <% %> and <%= %>.
Conditional Rendering in Asp.Net MVC Views
<% if(customer.Type == CustomerType.Affiliate) %>
<%= this.Html.Image("~/Content/Images/customer_affiliate_icon.jpg")%>
<% else if(customer.Type == CustomerType.Preferred) %>
<%= this.Html.Image("~/Content/Images/customer_preferred_icon.jpg")%>
<% else %>
<%= this.Html.Image("~/Content/Images/customer_regular_icon.jpg")%>

How to Simplify this Code Kludge

Input:
Id, PartId, Name
1, 1, Head
1, 2, body
1, 3, Tail
2, 1, Head
2, 2, Leg
Output Display:
- Head, Body, Tail [Delete(1)]
- Head, Leg [Delete(2)]
My Code:
<ol>
<%
int prev = -1;
foreach (var item in t)
{
if(prev != item.ResponseId){
if (prev != -1)
{%>
<%= Html.ActionLink("[replacethis]", "RemoveResponse", new { id = item.ResponseId })
.Replace("[replacethis]", "<img src=\"../../Content/images/delete_icon.gif\" class=\"borderlessImage\" title=\"Remove\"/>")%>
</li>
<%} %>
<li>
<% }
else {
%>, <%
} %>
<%= Html.Encode(item.ResponsePartValue) %>
<% prev = item.ResponseId;
} %>
<%= Html.ActionLink("[replacethis]", "RemoveResponse", new { id = prev })
.Replace("[replacethis]", "<img src=\"../../Content/images/delete_icon.gif\" class=\"borderlessImage\" title=\"Remove\"/>")%>
</li>
</ol>
Questions:
What are the ways to refactor this?
Any MVC tricks I am missing?
Well, first of all you could create an HtmlHelper that renders image links for you, instead of generating the anchor tags first and then replacing their content with an image.
Take a look at here.
Also you don't have to use <%= every time you need to ouput some text. If you already have opening code blocks (ie <%), then you can just use Response.Write method to output what you want. In cases like yours, that'll most likely look better than %> <%=.
Though, I admit I don't exactly know what you are listing here and how you want it to display. But following your algorithm, I guess this is what I would have done :
<ol>
<%
int prev = -1;
foreach (var item in t) {
if(prev != item.ResponseId) {
if (prev != -1) {
Response.Write(Html.ImageLink("../../Content/images/delete_icon.gif", "RemoveResponse", new { id = item.ResponseId, #class ="borderlessImage", title = "Remove" }) + "</li>");
}
Response.Write("<li>");
}
else {
Response.Write(", ");
}
prev = item.ResponseId;
Response.Write(Html.Encode(item.ResponsePartValue));
} %>
<%= Html.ImageLink("../../Content/images/delete_icon.gif", "RemoveResponse", new { id = prev, #class ="borderlessImage", title = "Remove" }) %>
</li>
</ol>
I would put everything into a dictionary, it would make your logic more logical :-)
Something like:
IDictionary<int, List<Part>> partsDictionary = new Dictionary<int, List<Part>>();
Where the int key is your id and then the value of type List would be your individual parts.
Then put the logic into a HtmlHelper extension.
E.g. (Although I don't know what you're doing, view code doesn't match you db model at the top. This should give you an idea)
public static string PartsList(this HtmlHelper html, IDictionary<int, List<Part>> partsDictionary)
{
if (partsDictionary.Count == 0)
return "";
StringBuilder toReturn = new StringBuilder("<ol>");
foreach (KeyValuePair<int, List<Part>> kvp in Model.PartsDictionary)
{
toReturn.Append("<li>");
//Individual part links
IList<string> partsLinks = new List<string>();
foreach (Part part in kvp.Value)
partsLinks.Add(html.ActionLink(part.PartName, "ActionName", new { #id = part.Id }));
toReturn.Append(string.Join(", ", partsLinks.ToArray()));
//Part category(?) link
toReturn.Append(html.ActionLink("Delete", "ActionName", new { #id = kvp.Key }));
toReturn.Append("</li>");
}
toReturn.Append("</ol>");
return toReturn.ToString();
}
Or something like that ;-)
HTHs
Charles

Resources