How do I construct an if statement within a MVC View - asp.net-mvc

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")%>

Related

Rails display value based on key in deep array of hashes

This is the array of hashes received as parsed_response from an API response which was XML, using Httparty.
Difficult and confusing to traverse inside and get the value.
"flights"=>{
"flight"=>{
"segments"=>{
"segment"=>[ (this has square brackets)
{
"index"=>"3",
"departure_airport"=>"DEL",
"arrival_airport"=>"CCU",
"departure_date_time"=>"2014-07-07T13:20:00",
"arrival_date_time"=>"2014-07-07T15:35:00",
"flight_number"=>"20",
"airline"=>"AI",
"operating_airline"=>"AI",
"stops"=>"0",
"equipment"=>"320",
"duration"=>"8100"
},
{
"index"=>"4",
"departure_airport"=>"CCU",
"arrival_airport"=>"BLR",
"departure_date_time"=>"2014-07-07T18:10:00",
"arrival_date_time"=>"2014-07-07T20:40:00",
"flight_number"=>"771",
"airline"=>"AI",
"operating_airline"=>"AI",
"stops"=>"0",
"equipment"=>"319",
"duration"=>"9000"
}
]
}
}
},
To display above hash values I did
<% h["flights"]["flight"]["segments"]["segment"].each do |o,p| %>
<% if o.class == Hash %>
<strong><%= o['airline'] %></strong>
<%= o['arrival_airport'] %> - <%= o['arrival_date_time'] %><br>
<% else %>
<%= o %>
<% end %>
<% end %>
(NOTE: Simply placing o['airline'] after loop would give can't convert String into Integer)
The else statement is to parse the below type of response.
"flights"=>{
"flight"=>{
"segments"=>{
"segment"=>{ (no square brackets)
"index"=>"3",
"departure_airport"=>"DEL",
"arrival_airport"=>"CCU",
"departure_date_time"=>"2014-07-07T13:20:00",
"arrival_date_time"=>"2014-07-07T15:35:00",
"flight_number"=>"20",
"airline"=>"AI",
"operating_airline"=>"AI",
"stops"=>"0",
"equipment"=>"320",
"duration"=>"8100"
}
}
}
},
So having <%= o %> after else statment, will give
["index", "7"] ["departure_airport", "DEL"] ["arrival_airport", "BLR"] ["departure_date_time", "2014-07-10T07:10:00"] ["arrival_date_time", "2014-07-10T09:50:00"] ["flight_number", "807"] ["airline", "9W"] ["operating_airline", "9W"] ["stops", "0"] ["equipment", "738"] ["duration", "9600"]
But having <% elsif o=="departure_airport" %> <%= p %> <% end %> in-place of else statement, will give the value associated with the key.
To get a single value using the key, this is fine. But it really gets messy to put all those key in the above format to get their values.
There should be a better way to parse it, but just cant figure out how will I deduce a use case where ['segment'] would give the result appropriately, based on if it is again a hash or it is just a key.
Thanks.
The solution here would be to wrap the Hash into an Array before looping it.
controller
#segments_array = Array.wrap(h["flights"]["flight"]["segments"]["segment"])
view
<% #segments_array.each do |segment| %>
<strong><%= segment['airline'] %></strong>
<%= segment['arrival_airport'] %> - <%= segment['arrival_date_time'] %><br>
...
<% end %>
[h["flights"]["flight"]["segments"]["segment"]].flatten.each do |segment|
puts "#{segment['arrival_airport']} - #{segment['arrival_date_time']}"
end
HTH

Rails best practice for displaying partial if condition is true

In my controller, I'm getting all of a user's associated #highinterest accounts, and I'm adding the sum of the value column:
#dohighinterest = Account.where(user_id: current_user, accounttype: 'Savings', name: ['GE Capital Bank', 'Barclays', 'CIT Bank', 'Bank5 Connect', 'Ally Bank', 'Discover', 'First Choice Bank', 'FNBO Direct', 'Mutual of Omaha', 'Sallie Mae Bank', 'American Express Bank', 'Capital One 360'])
#highinterest = #dohighinterest.sum(&:value)
Later on in the controller, I'm defining variables so that the view knows which class to render.
if #highinterest > (#rechighinterest * 0.8) && (#highinterest < (#rechighinterest * 1.2))
#highrec = "pass"
elsif #highinterest > (#rechighinterest * 0.6) && (#highinterest < (#rechighinterest * 1.4))
#highrec = "okay"
else
#highrec = "fail"
end
Here's the view:
<div class="rollup <%= #highrec %>">
<p>You're gaining interest on</p>
<div class="percentage">
$<%= number_with_delimiter(#highinterest, :delimiter => ',') %>
</div>
</div>
Additionally, I'd like to render a partial in the view if #highrec = "fail" and #highinterest = 0.
What's the best practice for putting that logic into the controller and view? I attempted to define a new variable in the controller #rectext = true if it meets that condition. Then in the view, I wrapped the partial reference to an <%= if #rectext = true %>, but that wasn't returning anything.
I don't think you need a separate variable to hold value of #highrec == "fail" && #highinterest == 0. You can use this same condition in your view. If however there are more variables in play, you could introduce a variable to keep the view cleaner!
<% if #highrec == "fail" && #highinterest == 0 %>
<%= render partial: 'path_to_other_partial' %>
<% else %>
<div class="rollup <%= #highrec %>">
<p>You're gaining interest on</p>
<div class="percentage">
$<%= number_with_delimiter(#highinterest, :delimiter => ',') %>
</div>
</div>
<% end %>
The line you tried <%= if #rectext = true %> would result in syntax error because of <%= tag, which is trying to output the value returned by if #rectext = true. So, a point to note would be, using <%= tag is going to output the value returned by the statements within the tags and <%(without the equals) is going to evaluate only without printing!
Secondly, you are assigning #rectext = true in the if statement, it should be a comparision, i.e. either if #rectext == true or just if #rectext.
You can define a helper method inside folder app/helpers/controllername_helper.rb that recieves the values of #highrec and #highinterest as parameters and then returns true or false depending on your needs.
Then in the view call the method this way:
<% if helper_method_name(#highrec, #highinterest) %>
<%= render partial: 'partial_path' %>
<% end %>
Note that in this code you write :
<%= if #rectext = true %>
you are assigning #rectext the value true and not checking if it is true. Also in this case you should use <% instead of <%=

In an action can I select a partial view to include in my view?

I have an action that receives the result of a radio button selection. From that I want to select which partial view to render in the resulting view.
i.e.
if radiobutton =1
render view with partial1
else if radiobutton =2
render myview with partial2
Is this possible?
Sure, just dump the value (or a boolean or whatever else you want to make it more readable) into the ViewBag or ViewData or ViewModel, then read from it on your view:
#if (Model.RadioButtonValue == 1) {
#Html.Partial("Part1")
} else {
#Html.Partial("Part2")
}
or
<% if ((string)ViewData["radiobutton"] == "1") { %>
<%= Html.Partial("Part1") %>
<% } else { %>
<%= Html.Partial("Part2") %>
<% } %>
You could also put the name of the partial itself in the ViewBag/ViewData/ViewModel, rather than having the conditional in the view:
#Html.Partial(Model.ThePartialName)

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(", ")

Char equals to String

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.

Resources