autoNumeric plugin error in asp.net MVC 5 - c#

I'm currently using autoNumeric in my application.
It works great.
However, in edit mode, JQuery is showing this error message:
The value ($ 100.000.00) being 'set' is not numeric and has caused a error to be thrown
I've something like this:
public string Amount { get; set; }
#Html.TextBoxFor(model => model.Amount, new { #class = "form-control", #placeholder = ModelMetadata.FromLambdaExpression(x => x.Amount, ViewData).Watermark })
$.extend($.fn.autoNumeric.defaults, {
aSep: '#System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator',
aDec: '#System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator'
});
$("#Amount").autoNumeric('init', { aSign: "$ " });
I have search for the error and found this
but that didn't help me.
Thanks for the help!

When I enter the value, during creation it is entered as $ 100,000.00
and that is save to the database just like that.
However, I have updated my code to remove the symbols before saving.
var amount = String.Join("", model.Amount.Split('$', ','));
So if $ 100,000.00 is entered, it is saved as 100000.00
and that fixed the issue.

Related

MVC call a resources file inside a property

i want to make the error message displayed localized through showing the error message from a resource file in 'Oninvalid' property and here is my code:
#Html.TextAreaFor(x => x.Message, new { #class = "form-control notifi-form-field", #name = "Message", #id = "MessageText",#oninvalid= "this.setCustomValidity('Resources.LayoutResources.RequiredField')"})
the Resources.LayoutResources.RequiredField is displayed as it is.
This is simply a string literal being sent from server-side code to client-side code:
"this.setCustomValidity('Resources.LayoutResources.RequiredField')"
The reference to the resource needs to be interpreted by the server-side code, so it needs to know that it's not just a string literal. For example:
$"this.setCustomValidity('{Resources.LayoutResources.RequiredField}')"
Or with older syntax:
"this.setCustomValidity('" + Resources.LayoutResources.RequiredField + "')"
Note that the single-quotes are still there for the resulting client-side code to be valid after the server-side code emits the string value.

I want to let my text box allow only text

I'm working on project using MVC3 + Razor.I want to let my text box allow only text. I tried to apply data annotation in my data model (First Code):
[DataType(DataType.Text ,ErrorMessage ="Error")]
but, it's not working.Could anyone help me ?
You need a regular expression as below:
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Please input letters only")]
You could annotate your model like this:
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
string TextBoxData {get; set;}
Then in your view you would use the helper
#Html.EditorFor(model => model.TextBoxData)
#Html.ValidationMessageFor(model => model.TextBoxData )

Binding lost on #Html.EditorFor when I apply formatting

When using the following I lose the binding on the field
#Html.EditorFor(model => model.Quote.DiscountRate, new { #class = "form-control pull-left " })
And the model field looks like this:
[DisplayFormat(DataFormatString = "{0:P2}",ApplyFormatInEditMode =true)]
public double? DiscountRate { get; set; }
if I remove the DisplayFormat the binding still works.
I also tried the following with the same result:
#Html.TextBoxFor(model => model.Entity.DiscountRate, "{0:P2}", new { #class = "form-control pull-left" })
In both cases if I remove the formatting I get my binding back
What I have discovered is that when you apply a DisplayFormat, it is as the name suggests, for display. If you want to display a decimal value with formatting and make it available for editing, you have to handle the conversion from text back to decimal at post time -- or whenever you need the actual value.

Calling a method in Razor ASP.NET MVC

I am a newbie at MVC and having trouble displaying the result of a certain method in a view input field. I am not too sure if I am supposed to create the method in the cshtml or in a separate cs file.
I have used the #function tag to create my method in a cshtml file below
#functions{
public int DaysCalc(DateTime first, DateTime second)
{
QuoteApp.Models.Quote ts = new QuoteApp.Models.Quote();
ts.StartDate = first;
ts.EndDate = second;
int days;
days = (second.Day - first.Day);
return days;
}
}
I am calling it this way in the cshtml file
#Html.EditorFor(model =>model.DaysCalc(model.StartDate, model.EndDate), new { htmlAttributes = new { #class = "form-control", disabled = "disabled"} })
I get an error stating
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Source Error:
Line 63: #Html.LabelFor(model => model.noOfDays, htmlAttributes: new { #class = "control-label col-md-2" })
Line 64: <div class="col-md-10">
Line 65: #Html.EditorFor(model =>#DaysCalc(model.StartDate, model.EndDate),new { htmlAttributes = new { #class = "form-control", disabled = "disabled"} })
Line 66: #Html.ValidationMessageFor(model => model.noOfDays, "", new { #class = "text-danger" })
Line 67: </div>
Source File: Line: 65
If you want to use EditorFor, create a property that returns your calculated value.
public class YourModel
{
public int CalculatedDays
{
get
{
QuoteApp.Models.Quote ts = new QuoteApp.Models.Quote();
ts.StartDate = first;
ts.EndDate = second;
return (ts.EndDate - ts.StartDate);
}
}
}
#Html.EditorFor(model => model.CalculatedDays, new { htmlAttributes = new { #class = "form-control", disabled = "disabled"} })
You can only use the For methods with actual properties on your model (i.e. not functions). I'm not sure what you're actually trying to achieve by doing this, so I can't really help you further unless you update your question, but that explains your error at least.
EDIT
First and foremost, I need to point out that your date calculation is not correct. What if StartDate is 2014-06-30 and EndDate is 2014-07-01. Then the result of is going to 1 - 30 = -29. I'm reasonably sure that's not what you're looking for. There's a method on DateTime just for this purpose:
TimeSpan difference = EndDate.Subtract(StartDate);
The result is a TimeSpan, which you can then call difference.Days to get the number of days involved. Also of note, there's a TotalDays property off TimeSpan that will return fractional days (whereas Days just returns whole days).
Next, for what it's worth, and since you're new to all this, the in-view Razor helpers are a nice novelty, but they're impractical to the point of being useless, and frankly, they violate MVC (the pattern, not the framework from Microsoft). If you need to do this type of calculation, the best place for it is on your model. You can implement a property like:
public int Days
{
get
{
return EndDate.Subtract(StartDate).Days;
}
}
However, that's read-only (there's no setter method), and if you're talking about using this as an input value, it doesn't make sense to have a read-only property backing it (unless, I guess, if you make it a read-only input, in which case it might as well just be plain-text). So, if this is something you intend to post back to you'll need to figure out what that means in terms of a setter. Honestly, I can't see what you would do with that because the only logical thing to do is have it set values for StartDate and EndDate, and you can't do that without some point of reference. You could require StartDate to be set, and then take a value for Days and then use that to calculate EndDate, but it all boils down to what your business requirements are.
Add the Days property to your view model and store the result of the DaysCalc on it.
Then you can use it like:
#Html.EditorFor(model =>model.Days, new { htmlAttributes = new { #class = "form-control", disabled = "disabled"} })
Try creating a property on your model (this is assuming you are using a typed model, not a dynamic one):
public int Days
{
get {
QuoteApp.Models.Quote ts = new QuoteApp.Models.Quote();
ts.StartDate = StartDate;
ts.EndDate = EndDate;
int days;
days = (EndDate.Day - StartDate.Day);
return days;
}
}
Usage:
#Html.EditorFor(model => model.Days, new { htmlAttributes = new { #class = "form-control", disabled = "disabled"} })
I'm not sure if EditorFor will work quite right with a readonly property or not, but it looks like you are just using it for display or some other purpose anyway?
Also, I'm not sure what you are using the Quote object for, since it doesn't appear you are doing anything with it other than creating it, so this could be possibly simplified into:
public int Days
{
get {
return EndDate.Day - StartDate.Day;
}
}

Provide value to htmlAttributes where keys contain dash in their name in MVC view (e.g. "data-bind")

Most of the Html helpers available in ASP.Net MVC have overloads with object htmlAttributes. This is used to provide additional attribute values for the outputted tags. While using the anonymous object notation for specifying htmlAttributes value, their property names must be valid c# identifier.
Now the problem arises when you are trying to output a property with a dash - character (for e.g. knockout js's "data-bind" attribute)
So for example lets take the following example:
#Html.TextBox("Title", string.Empty, new { data-bind="text: title" })
Try the above code in your view and at run-time it would show error screen with below message:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
So the question is, how to provide htmlAttributes with their property keys having dash characters; like "data-bind"?
In your property names, replace all your dash - characters with an underscore _ (as shown in example below):
#Html.TextBox("Title", string.Empty, new { data_bind="text: title" })
This would work because all HTML helpers convert an underscore _ in a property name to a dash - when rendering the HTML; i.e. for your example, data_bind when outputted in html gets converted to data-bind.
This is not always correct. Say you're using parameters in a URL.
#Html.ActionLink("Add Job", "Index", "Home", new { foo_bar = "foobar" }, new { #class = "btn btn-default", data_foo = "bar" })
The data_foo does get rendered as "data-foo", but the parameters stays as a under bar. Your result will be: http://your.domain/yourapp/?foo_bar=foobar
Of course you can't actually use the dash or you get the error specified in the OP.
I have worked around this as follows, but I'd be interested to see if anyone that comes along in the future will have a better way:
#{
var link = Html.ActionLink("Add Job", "Index", "Home", new { foo_bar = "foobar" }, new { #class = "btn btn-default", data_foo = "bar" });
}
#Html.Raw(link.ToString().Replace('_', '-'))
Use the HtmlHelper.AnonymousObjectToHtmlAttributes method. The following code will add a tooltip to the text input box, with the tooltip displaying the data from the DisplayAttribute description for MyIntVal on my model.
#{
var htmlAttributesWithDashes = HtmlHelper.AnonymousObjectToHtmlAttributes(
new
{
id = "myTextBoxId",
data_toggle = "tooltip",
data_position = "left top",
title = ModelMetadata.FromLambdaExpression( m => m.MyIntVal, ViewData ).Description
}
);
}
<div class="col-sm-6">
#Html.TextBoxFor( m => m.MyIntVal, htmlAttributesWithDashes )
</div>

Categories

Resources