Asp.net mvc razor view string.format does not seems to work - asp.net

I am using string.format to format my model value inside razor view but it does not gives desired result
#string.Format("{0:00}", Model.Range == null ? "" : Model.Range.ToString())
It should result as 05
if i am using below it gives me result but not from model
#string.Format("{0:00}", 5)
Someone have any idea or same experience ?

If Model.Range is a number type then you need to write:
#string.Format("{0:00}", Model.Range == null ? "" : Model.Range)
because with the Model.Range.ToString() you have converted your Range to string so the number formatting cannot be applied because it is not a number anymore.
By the way string.Format handles null arguments so it is enough to write:
#string.Format("{0:00}", Model.Range)
If Model.Range is not a number but with Model.Range.ToString() you get a number in a string representation then you need to first convert it to a number (like using int.Parse or its other variants) then you can pass the number to string.Format which can now apply the correct formatting.

Related

Json Path logical NOT operator with Filter not working

I have JSON data and want to use the logical not operator in JSONPath, however, I want to use it dynamically since my input string consists of many filters which I convert into a JSONPath query.
v1/movie?filter=not metadata.sample eq "NETFLIX" this way I am using my APY. This should be converted to [?(!(#['metadata']['PLM-CODE'] == 'NETFLIX'))] using the Filter object of JSONPath.
Now this below one works perfectly
JsonPath.using(configuration).parse(jsonString).read("$.data[?(!(#['metadata']['PLM-CODE'] == 'NETFLIX'))]",typeRef);
but I can not directly add ! when using the code below:
String stringFilter = rightPred.toString();
String notFilterString = "[?(!" + stringFilter.substring(2,stringFilter.length()-1) + ")]";
return Filter.parse(notFilterString);
but parse is converting it to [?(#['metadata']['PLM-CODE'] == 'NETFLIX' ! null)]

Handle Null condition

I want to handle null condition in below code.
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
My code is getting break at
dataSet.Tables("History").Rows(0)("DiscountsAdjustments")
since its value is null. I want to replace null value with "0.00"
Please help how can I handle.
Thanks
Rahul,
You will likely need to rewrite this part of it. Here is your original code:
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
Instead of this big nested mess... why not do it this way. Note I dont have a VB debugger in front of me so there may be some slight format adjustments, so consider this pseudo code:
Is the dataset valid
If Not IsDBNull(dataSet.Tables("History"))
''We know that we have data in our dataset
''Do all your checks
if Not isDBNull(dataSet.Tables("History").Rows(0)("Your field"))
''Do something
Else
''Show a 0
END IF
''REPEAT THE ABOVE LINES FOR EACH FIELD
End if
You can check for null on any column first using methods on the DataRow object:
Which of IsDBNull and IsNull should be used?

Format zero currency value with {0:C} in VB.Net

I am trying to format a zero currency value as an empty string, so that when the currency value is 0.00 then an empty string gets displayed rather than $0.00.
This code is part of an ASP.Net app that will display currency value to end user.
I have used following code to achieve this goal.
Question : Is it possible to achieve this by just using {0:C} format string or another version of this format string instead of using if then else coding for this? If I use ###,###,###.## as the data format string then an empty string shows for zero currency value and also I get rid of the if then else coding but for non-zero values no currency symbol shows.
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
charValue = Nothing
Else
charValue = String.Format("{0:C}", CDec(currencyValue))
End If
UPDATE
I ended up using the following code, which is working fine. If is better than IIf because it does short-circuiting, which means that IIf will evaluate all expressions whether the condition is true or false but If will evaluate the first expression only if condition is true and evaluate the second expression only if condition is false.
Dim d As Decimal
Decimal.TryParse(currencyValue, d)
charValue = If(d = 0D, Nothing, String.Format("{0:C}", d))
I don't think there is a way using formatting to display an empty string.
But you can write it like:
charValue = If( currencyValue = 0D, "", currencyValue.ToString("C") )
using the If Operator (Visual Basic).
Also this is something I would not do:
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
If currencyValue is Decimal:
If (currencyValue = 0D) Then
If currencyValue is Double:
If (currencyValue = 0R) Then
Also, if you are using a database and this is a Sql Server mind SQL Server Data Type Mappings
I don't think you can when using C or the other similar standard formats, since they are already defining a culture-specific format that will include a format for zero.
But if you specify your own custom format, you can specify three different formats separated by ;s, one each for positive numbers, negative numbers, and zero, respectively.
For example (giving an empty string for the zero format, resulting in blank zeroes):
charValue = String.Format("{0:#,##0.00;-#,##0.00;""""}", CDec(currencyValue))
And from what I can see, omitting the format for negative gives a default that matches the positive, whereas omitting the format for zero gives blank, which is what you're looking for, so this should be sufficient as well:
charValue = String.Format("{0:#,##0.00;;}", CDec(currencyValue))
(Using whichever custom format you wish.)
UPDATE: You can get the current currency symbol and manually put it into your custom format. IE:
Dim symbol = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol
charValue = String.Format("{0}{1:#,##0.00;;}", symbol, CDec(currencyValue))
From the sound of it, though, I think I would actually recommend doing basically what you started with, maybe with an extension method.
<Extension>
Public Function ToCurrencyString(pValue As Decimal) As String
Return IIf(pValue = 0, "", pValue.ToString("C"))
End Function
Dim someValue As Decimal = 1.23
Console.WriteLine(someValue.ToCurrencyString())
This gives you exactly what you're looking for. The exact same format as C gives, but with blank zeroes.

Using ternary operator to output a string containing whitespace in Razor

I'm trying to use a ternary operator in Razor, similar to this question, but what I want to output contains whitespace. This code
#(selectedGoal == null ? "" : "value=" + selectedGoal.Name)
should produce
value="Goal 3"
as the value of selectedGoal.Name is "Goal 3". Instead, I get
value="Goal" 3
which is no good. I've tried a bunch of different combinations of escaped quotes, # symbols and no # symbols, and I just can't get this to work, i.e.
#(selectedGoal == null ? "" : "value=" + "selectedGoal.Name")
#(selectedGoal == null ? "" : "value=#selectedGoal.Name")
and then I just get something like
value="selectedGoal.Name"
Anyone know how this should be done?
Your value attribute is missing its own quotes, so they are being automatically added before the space. Try moving value outside of the expression.
value="#(selectedGoal == null ? "" : selectedGoal.Name)"
What about
#(selectedGoal == null ? "" : "value=\"" + selectedGoal.Name + \")
Or you can try rendering them directly as an HTML block, using my method on
Html literal in Razor ternary expression

How can I tell if E4X expression has a match or not?

I am trying to access an XMLList item and convert it to am XML object.
I am using this expression:
masonicXML.item.(#style_number == styleNum)
For example if there is a match everything works fine but if there is not a match then I get an error when I try cast it as XML saying that it has to be well formed. So I need to make sure that the expression gets a match before I cast it as XML. I tried setting it to an XMLList variable and checking if it as a text() propertie like this:
var defaultItem:XMLList = DataModel.instance.masonicXML.item.(#style_number == styleNum);
if(defaultItem.text())
{
DataModel.instance.selectedItem = XML(defaultItem);
}
But it still give me an error if theres no match. It works fine if there is a match.
THANKS!
In my experience, the simplest way to check for results is to grab the 0th element of the list and see if it's null.
Here is your code sample with a few tweaks. Notice that I've changed the type of defaultItem from XMLList to XML, and I'm assigning it to the 0th element of the list.
var defaultItem:XML =
DataModel.instance.masonicXML.item.(#style_number == styleNum)[0];
if( defaultItem != null )
{
DataModel.instance.selectedItem = defaultItem;
}
OK I got it to work with this:
if(String(defaultItem.#style_number).length)
Matt's null check is a good solution. (Unless there is the possibility of having null items within an XMLList.. probably not, but I haven't verified this.)
You can also check for the length of the XMLList without casting it to a String:
if (defaultItem.#style_number.length() > 0)
The difference to String and Array is that with an XMLList, length() is a method instead of a property.

Resources