MVC call a resources file inside a property - c#

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.

Related

autoNumeric plugin error in asp.net MVC 5

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.

Disabled DateTime field is marked as required in MVC4 page

One of my models contains a property which looks like this
private Nullable<DateTime> myDate;
[Display(Name = "My Date")]
[Editable(false)]
// [DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
public DateTime MyDate
{
get { return this.myDate?? new DateTime(1, 1, 1); }
set { this.myDate = value; }
}
// [DataType(DataType.Date)] is commented out because it's a leftover from some experiments I made.
In my "edit" view I render the property like this
// input.noborder { border: 0 none; }
#Html.EditorFor(model => model.MyDate, new { #readonly = true, #class = "noborder" })
#Html.ValidationMessageFor(model => model.InvoiceDate)
I did not create an EditorTemplate for DateTime type. Finally, in the scripts of the same view, I attach jQuery Datepicker
var $dpMyDate = $('[name=MyDate]');
$dpMyDate.datepicker();
I basically want to render a read-only datepicker (next step would be to implement more scripts which would enable it if some conditions are met).
Everything seems to work but upon clicking the "save" button, validation tells me that the field is required, but I expected it not to be, since I didn't put the [Required] attribute in the class. Also (but this might just be me assuming too much) it feels weird that a readonly input field would be required (how is one supposed to fill it?)
I don't see anything wrong with the code, am I missing something ?
From reading the comments it looks like you failed at the javascript validation that ASP.NET MVC adds. The issue is that, while your private field is nullable, the property is non-nullable (DateTime is a struct). ASP.NET MVC binds to the property and concludes that it is "Required" even though it's not marked as [Required].
As a result, ASP.NET MVC will generate javascript as if it were marked as a [Required] property. In particular, you used an EditorFor() and so the javascript ASP.NET MVC injects will treat it as required. Since it's a readonly form element I believe the javascript will complain.
The way to get around this is to use a DisplayFor() which doesn't have that javascript attached.
Note that if you have a nullable property that is [Required] but you don't want it to be editable, you'll actually need to do something extra in addition to using DisplayFor()--you'll need to submit something in the HTTP request that ASP.NET MVC knows how to model bind. The most popular option is an <input> element with type=hidden. Because the user has absolute control over the HTTP request he sends to the server, you would probably want to ignore the submitted value to prevent "overposting".
Try this,
Change this
#Html.EditorFor(model => model.MyDate, new { #readonly = true, #class = "noborder" })
to
#Html.TextBoxFor(model => model.MyDate, new { #readonly = true, #class = "noborder" })
And remove #Html.ValidationMessageFor(model => model.InvoiceDate) it's no need.
I think its because your date not Nullable.
Try to define it like
public DateTime? MyDate

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>

PlaceHolder + #Html.TextBox issue

The goal
Apply, with success, the placeholder attribute for #Html.Textbox method.
The problem
There is the following syntax on my application;
#Html.TextBox("term", new { placeholder = "What are you searching for?" })
But, when the TextBox is rendered, the value attribute of the input is placeholder = "What are you searching for?". In other words, the placeholder attribute isn't applied as an attribute, but as an input's value.
Knowledge
I already searched about this question on Google and Stack Overflow, but until now, without success.
This link has a solution with the same syntax that I'm using, but when I pass the second parameter to TextBox(), it is rendered as a value and nothing happens with the third parameter (in our case, new { placeholder = "something" }).
You're calling the string name, object value overload of that method, so the second parameter is being taken as the value, not as htmlAttributes. You should use a different overload of the method, probably string name, object value, object htmlAttributes by specifying an empty value:
#Html.TextBox("term", "", new { placeholder = "What are you searching for?" })
try this for an empty #Html.TextBox
#Html.TextBox("CustomarName" ,null, new { #class = "form-control" , #placeholder = "Search With Customar Name" })
There is a third param you need:
#Html.TextBox("term", Model.SomeProperty, new { placeholder = "What are you searching for?" })
The third param are any attributes you wish to include in the HTML output of the input field.

Html.TextBoxFor formatting or Html.EditorFor htmlAttributes?

I am kind of stumped because, I want to format the value and add a html attribute for css class.
If I use #Html.TextBoxFor(m => m.DateModified)
- I can add html attribute but formatting does not work via DisplayFormat attribute on the member.
If I use #Html.EditorFor(m => m.DateModified)
- Formatting works but I cannot add html attribute
If I use #Html.TextBox("DateModified", Model.DateModified, ...)
- I get null reference exception when Model is null when the form is in add mode
What is the best way to achieve this?
I ended up solving this by creating a custom editor template for my date picker as so:
Shared/EditorTemplates/DateTime.cshtml
#model System.DateTime?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : string.Empty, new { #class = "date-picker" })
Then in my original page continue to use
#Html.EditorFor(m => m.DateModified)
You could...
#Html.TextBoxFor(m => m.DateModified, new { Value = Model.DateModified.ToString("MM-dd-yyyy"), #class = "superCoolClassName"})
Use #Html.EditorFor(m => m.DateModified), because otherwise the DisplayFormat attribute will have no effect.
To add further attributes like a CSS class, you have to create an editor template for the DateTime.
Create a file EditorTemplates/DateTime.cshtml with the following content:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new
{
#class="date"
})
Please note that the value of the TextBox is not set with the Model directly, but rather with the TemplateInfo.FormattedModelValue, because that value will be formatted according to the DisplayFormat attribute while the Model not. (This took me quite some time to realize. :))
In simple cases this might be enough, e.g. if the CSS class can be the same for all date editors.
If you want to parametrize the attribute, you can do that as well, passing the attribute value parameter to the EditorFor.
#Html.EditorFor(m => m.DateModified, new { #class = "someClass" })
However, this parameter will be not automagically delegated to the HTML control as attribute, but you have to "handle it" in the template explicitly. According to my experiences you can access this parameter value in the ViewData in the template, so the parametrized template looks like this:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new
{
#class=ViewData["class"]
})
To prevent hardcoding the key/value pairs listed in EditorFor , convert the ViewData object to a Dictionary and pass that dictionary object to TextBox.
eg
#Html.EditorFor(m => m.DateModified, "Template", new { #class = "someClass", size=8 , htmlTag="custom" })
And in the template you have
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData.ToDictionary(c=>c.Key,c=>.Value))
To show json date in textbox (cshtml):
var d1 = ui.item.IssueDate;
var d = new Date(parseInt(d1.slice(6, -2)));
var Issdate = ("0" + (d.getMonth() + 1)).slice(-2) + '/' +
("0" + d.getDate()).slice(-2) + '/' +
d.getFullYear().toString();
$('#IssueDate').val(Issdate);

Categories

Resources