How can I given restriction only to accept two decimal place or how can I format with only two decimal place . I tried with model RegularExpression(#"^\d+.\d{0,2}$" and I tried #step 01 and tabindex 7, still not working , we can give more than two numbers for decimal . Here is the code
#Html.TextBoxFor(m => m.attendanceLogList[i].NormalHrs, new
{
#class = "form-control input-sm emphrs",
#style = columnstyle,
#Value = Model.attendanceLogList[i].NormalHrs,
#type = "number",
#step = ".01",
onchange = "CalculateTotal(this);"
})
Assuming the onchange event CalculateTotal(this); is a javascript function. IMHO, applying the javascript as below into your Razor snippet, in the same way, should work, FYI.
function fixDecimal(e) {
return e.value = e.value.toString().match(/^\d+(?:\.\d{0,2})?/);
}
<input type="number" step="0.01" onkeyup="fixDecimal(this)" />
Related
I have an HTML input that indicates a year as so:
<input type="number" name="year" placeholder="Year" [max]="presentYear" min="1950">
The input is not required, so by default I simply want the placeholder "Year" to be present. However, as soon as the user clicks on the up or down arrows of the input field, I want the max value to be shown as default, in this case the present year (2018). However, the minimum number is shown instead. This makes no sense for this situation, since the user would have to scroll through 68 years to get to the most common use case.
Is there any way to specify the default "first value" of a number type input field? If it helps answer the question, I'm using Angular 5 for this project.
You can set min to the same value as max initially, and change it for 1950 after the input value has been changed, with the help of ngModel and ngModelChange. The first click on the spinner button will set the current year as the initial value, and the modified min value will allow to change it afterwards.
<input type="number" name="year" placeholder="Year"
[(ngModel)]="year" (ngModelChange)="setMinYear($event)"
[max]="presentYear" [min]="minYear">
export class AppComponent {
presentYear = this.getCurrentYear();
minYear = this.getCurrentYear();
year: number;
private getCurrentYear(): number {
return new Date().getUTCFullYear();
}
public setMinYear(value: number) {
const firstYear = 1950;
if (value >= firstYear) {
this.minYear = firstYear;
} else {
this.minYear = this.presentYear;
}
}
}
The code can be tested in this stackblitz.
in JS:
dateObj: Date = new Date();
year: number = dateObj.getUTCFullYear();
yearModel: number = year;
in HTML
Bind property to your input control , as given in below code it will do for you
<input type="number" name="year"
placeholder="Year"
[(ngModel)] = "yearModel"
[max]="year"
min="1950">
A separate Model prevents the value to go over the current year
I am trying to generate a unique label and and input text box for a partial view that is being used to render a list of user input rows.
By unique I mean that each input text box should have its unique html "id" and "name" so that when is submitted each input can be identified
In the View I have
#model UserDataModel
#{
var inpName = "benefName" + #Model.Row;
var inpAge = "benefAge" + #Model.Row;
}
#Html.LabelFor(x => x.Name, new { #class="labelhalf"})
#Html.EditorFor(x => x.Name, new { id = #inpName, htmlAttributes = new { #class = "form-control animated" } })
When the view is being render this is what I am seeing
<label class="labelhalf" for="Name">Nombre (Opcional)</label>
<input class="text-box single-line" id="Name" name="Name" type="text" value="">
As you can see the "name" and "id" attributes of the text input is "Name" and "Name" and is not using the value of the #inpName variable ("benefName1" for example)
Also I am trying to assign some CSS classes to that same input using "htmlAttributes"
I had previously tried this with this approach
<label form="FormStep_01" for=#inpName class="labelhalf">Nombre (Opcional)</label>
<input form="FormStep_01" id=#inpName class="form-control animated" pattern="^[_A-z0-9]{1,}$" type="text" placeholder="" required="">
...but the content of the input fields with this approach are not being submited and that is the reason I am trying to use the #Html.EditorFor
UPDATE
I am now using the TextBoxFor which takes the "id" and the "class" fine but not the "name" which is used in the submit
#Html.LabelFor(x => x.Name, new { #class = "labelhalf" })
#Html.TextBoxFor(x => x.Name, new { #id = #inpName, name = #inpName, #class = "form-control animated" })
Please let me know how to achieve this in MVC4
Issue 1 (Using EditorFor())
You cannot add html attributes using EditorFor() in MVC-4. This feature was not introduced until MVC-5.1, and then the correct usage is
#Html.EditorFor(m => m.SomeProperty, new { htmlAttributes = new { someAttribute = "someValue" }, })
Issue 2 (Using TextBoxFor())
You cannot change the value of the name attribute using new { name = "someValue" }. The MVC team built in a safe guard to prevent this because the whole purpose of using the HtmlHelper methods to generate form controls is to bind to your model properties, and doing this would cause binding to fail. While there is a workaround, if you do discover it, don't do it! As a side note - the following line of the private static MvcHtmlString InputHelper() method in the source code
tagBuilder.MergeAttribute("name", fullName, true);
is what prevents you overriding it.
Issue 3 (Manual html)
You not giving the inputs a name attribute. A form posts back a name/value pair based on the name and value attributes of successful controls, so if there is no name attribute, nothing will be sent to the controller.
Side note: If your manually generating html, there is no real need to add an id attribute unless your referring to that element in javascript or css.
Its unclear why your trying to create a input for something that does not appear to relate to your model, but if your trying to dynamically generate items for adding items to a collection property in your model, refer the answers here and here for some options which will allow you to bind to your model.
I have a project written in C# MVC using Razor templates. On one of my pages I have several input fields that contain numeric values. The Razor code that sets the values of these input fields looks like this:
#Html.Editor(Model.DesignParams[i].ParamId,
new {
htmlAttributes = new
{
#Value = Model.DesignParams[i].DefaultValue,
#class = "form-control text-right",
#type = "text",
id = "_" + Model.DesignParams[i].ParamId,
uomid = Model.DesignParams[i].UOMId,
measureid = Model.DesignParams[i].MeasureId
}
})
The above code works fine using FireFox and Chrome and generates an input field that looks like this:
<input type="text" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad"
id="_HeatOfRejection" class="form-control text-right text-box single-line"
value="5000.0">
But the same Razor code, identical #Model values viewed with IE generates this:
<input Value="5000" class="form-control text-right text-box single-line"
id="_HeatOfRejection" measureid="HeatLoad" name="HeatOfRejection"
type="text" uomid="MBH" value="" />
As you can see, there is a difference between the value= attribute generated for IE in that the value attribute that gets my actual value begins with an uppercase 'V' and the lowercase value is an empty string. I'm stumped on this...
Can anyone tell me why this is happening and possibly how to handle it?
This difference effects jQuery's ability to return the input's value with:
var value = $(inputfield).attr("value");
Maybe .val() will retrieve the input field value, but this is going to require a rewrite of core jQuery code that supports this page and others, so I wanted to ask if anyone can tell me why this 'Value=' gets created for IE only and if there is a way of overcoming the problem.
Update:
Changing #Value to #value (or just value) results in an empty value attribute in Firefox and IE:
<input type="text" value="" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad"
id="_HeatOfRejection" class="form-control text-right text-box single-line">
As StuartLC points out, you are trying to get Html.Editor to do something it wasn't designed to do.
What happens when you pass a #value or #Value key to the htmlAttributes is that the rendering engine produces an attribute with that name in addition to the value attribute it's already generating:
<input type="text" name="n" value="something" value="somethingElse" />
or
<input type="text" name="n" value="something" Value="somethingElse" />
In both cases, you're giving the browser something bogus, so it can't be expected to exhibit predictable behavior.
As alluded above, Html.Editor has functionality to generate the value attribute based on the expression argument you pass to it. The problem is that you are using that incorrectly as well. The first argument to Html.Editor() needs to be an expression indicating the model property that the editor should be bound to. (e.g. the string value "DesignParams[0].ParamId") Nowadays, the preferred practice is to use the more modern EditorFor that takes a lambda function, as StuartLC showed in his post:
#Html.EditorFor(model => model.DesignParams[i].ParamId, ...)
You are "capitalising" the value html attribute. Change this to lower case...
#Value = Model.DesignParams[i].DefaultValue
as below ...
#value = Model.DesignParams[i].DefaultValue
IE is not the smartest of web browsers and there's definitely something wrong in the way Trident (they're parsing engine) validates elements' attributes as seen in these threads...
https://github.com/highslide-software/highcharts.com/issues/1978
Highcharts adds duplicate xmlns attribute to SVG element in IE
Also, as already noted somewhere else. What's the need for the Editor extension method? Isn't it simpler to just use TextBoxFor instead?
#Html.TextBoxFor(model => model.DesignParams[i].ParamId
, new
{
#class = "form-control text-right"
, uomid = Model.DesignParams[i].UOMId
, measureid = Model.DesignParams[i].MeasureId
})
Editor works with metadata. then you need to more about this,
http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-2D00-ASP.Net-MVC-2.0-Beta_2D00_1.aspx
But the easiest way is go with
#model Namespace.ABCModel
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(model => model.DesignParams[i].ParamId, new { #class = "form-control text-right", uomid = Model.DesignParams[i].UOMId, measureid = Model.DesignParams[i].MeasureId })
}
You shouldn't be using invalid Html attributes in this way. Use the data- attributes in Html 5.
Also, your use of #Html.Editor(Model.DesignParams[i].ParamId (assuming ParamId is a string) deviates from the helper's purpose, which is to reflect the property with the given name off the Model, and use the value of this property as the Html value attribute on the input. (MVC will be looking for a property on the root model with whatever the value of ParamId is, which seems to silently fail FWR)
I would do the defaulting of Model.DesignParams[i].ParamId = Model.DesignParams[i].DefaultValue in the Controller beforehand, or in the DesignParams constructor.
#Html.EditorFor(m => m.DesignParams[0].ParamID,
new {
htmlAttributes = new
{
// Don't set value at all here - the value IS m.DesignParams[0].ParamID
#class = "form-control text-right",
#type = "text",
id = "_" + Model.DesignParams[i].ParamId,
data_uomid = Model.DesignParams[i].UOMId,
data_measureid = Model.DesignParams[i].MeasureId
}
Note that this will give the input name as DesignParams[0].ParamID, which would be needed to post the field back, if necessary.
Here's a Gist of some example code
(The underscore will be converted to a dash)
Use data() in jQuery to obtain these values:
var value = $(inputfield).data("uomid");
I have an EditorFor razor defined input box that sets the value for "Hours" that has it's data model bound:
#Html.EditorFor(modelItem => item.Hours, null, "weeklytargets[" + item.WeeklyTargetId + "].Hours")
When it's spit out to HTML it looks like so:
<input class="text-box single-line" data-val="true" data-val-number="The field Hours must be a number." id="weeklytargets_17__Hours" name="weeklytargets[17].Hours" type="number" value="10">
How can I add attributes min and max for this input box of type number?
Try using the additionalViewData parameter to pass in htmlAttributes. This way you can specify a min and max value:
#Html.EditorFor(
expression: modelItem => item.Hours,
templateName: null,
htmlFieldName: "weeklytargets[" + item.WeeklyTargetId + "].Hours",
additionalViewData: new
{
htmlAttributes = new
{
min = 0,
max = int.MaxValue
}
})
This is working for me
#Html.TextBoxFor(m => m.years_completed, new { #type="number", min = "1", max = "10" })
In MVc I am using Html.TextboxFor() control
I have input type control as below.
<input id="phoneNumber" type="text" class="phoneNumber form-control" value="#actorPhone.PhoneNumber" data-phoneType ="#actorPhone.PhoneTypeTd" data-actorId ="#Model.ActorId" maxlength="30"/>
I want to change this intput control to MVC
#Html.TextBoxFor(m=>m.phoneNumber,new {#class = "phoneNumber", maxlength = "30"})
How I can add data-phoneType and data-actorId properties to the html control, as - is not allowed in the properties of HTML Attribute.
use an underscore _
the Razor engine is smart enough to render the underscore within the property name to the corresponding dash sign, resulting in your desired HTML5-like attributes
example:
#Html.TextBoxFor(m=>m.phoneNumber,
new {#class = "phoneNumber", maxlength = "30",
data_phoneType = YOUR_VALUE_HERE,
data-actorId=YOUR_VALUE_HERE })
and this should result in your desired output.
hope this helps :)
You can set an underscore instead and Razor will render it like a minus/dash:
#Html.TextBoxFor(m => m.phoneNumber,
new { data_phoneType = "phone type",
#class = "phoneNumber",
maxlength = "30"})
Use data_* attributes like
#Html.TextBoxFor(m=>m.phoneNumber,
new {
data_phoneType=actorPhone.PhoneTypeTd,
#class = "phoneNumber",
maxlength = "30"
})