I am having issues with html.textboxfor when i have to insert a decimal into my db, which is also set to a decimal.
i have tried this:
[RegularExpression(#"^[0-9]+(\.[0-9]{1,3})$", ErrorMessage = "Valid Decimal number with maximum 3 decimal places.")]
but it will only accept it if i have at least 3 decimals (1,123).
i need it to be able to accept, {1 - 1,2 - 1,23 - 1,234}
how do i achieve this ?
i have not been able to find a regularexpression generator which i could figure out how to use..
or am i in completely the wrong direction as to how i am going to solve my issue?
my value in the model:
[RegularExpression(#"^[0-9]+(\.[0-9]{1,3})$", ErrorMessage = "Valid Decimal number with maximum 3 decimal places.")]
[Required]
public decimal Average { get; set; }
input html in my form:
<div class="form-group">
#Html.LabelFor(x => x.Average, "Gennemsnit")
#Html.TextBoxFor(x => x.Average, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Average, "", new { #class = "text-danger" })#
</div>
Update
It was indeed as StephenMuecke said, that i needed to change $.validator in jquery validator.
so i added this:
(function () {
$.validator.methods.number = function (value, element) {
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:.\d{3})+)?(?:\,\d+)?$/.test(value);
}
})();
to overwrite the method.
Related
I have a problem with the valitation of the DataType.Date in a GERMAN format 0:dd.MM.mm.yyyy.
Model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "LogEntry")]
public DateTime LogEntry { get; set; }
View
#Html.LabelFor(model => model.LogEntry)
#Html.TextBoxFor(model => model.LogEntry, "{0:dd.MM.mm.yyyy}", new { #class = "form-control" , #Value = #DateTime.Now })
#Html.ValidationMessageFor(model => model.LogEntry, "", new { #class = "text-danger" })
The day value is changed in the valitation with the month value. Is that the reason why the validation release??
This picture shows the day value bigger than 12
Message in english: "The Edit Time field must be a date"
This picture shows the day value lesser than 13
#Html.ValidationMessageFor(model => model.LogEntry, "", new { #class = "text-danger" })
Here are my questions.
Does someone knows where the default messages of the validation comes from ?
Does someone knows where I can switch of the validation?
Does someone knows how to solve the problem?
My SQL database has a column Date which allows strings only in such format: __/____, basically month/year for example: 01/2019.
Is it possible for my:
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
to have some helper so that user can type only using the correct format? For example the editor which has strong typed something like this: __/___ and can only input numbers to fill underscores.
#Html.TextBoxFor(m => m.StartDate,
new { #Value = Model.StartDate.ToString("yyyy/MM/dd"), #class="datepicker" })
I have #Html.DropDownList which take data from controller in edit mode. I need to hide DropDown element and show some message if list is null or empty.
I try with this code in view, but all the time give me result thet have, and show empty dropdown:
#if(ViewBag.DatumRID != null)
{
<div class="col-md-10">
#Html.DropDownList("DatumRID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DatumRID, "", new { #class = "text-danger" })
</div>
}
else
{
<h6 style="color:#ff0000"> NO RECORDS.</h6>
}
And code from controller is here:
ViewBag.DatumRID = new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID);
when record fount dropdown is ok, but when record is null dropdown show empty.
Check list size also. For correct displaying data SelectList must contain more than zero items. Try this:
#if(ViewBag.DatumRID != null && ViewBag.DatumRID.Count > 0)
{
<div class="col-md-10">
#Html.DropDownList("DatumRID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DatumRID, "", new { #class = "text-danger" })
</div>
}
else
{
<h6 style="color:#ff0000"> NO RECORDS.</h6>
}
Update:
U may try update your controller code like this:
List<SelectListItem> viewList = new List<SelectListItem>();
viewList.AddRange(new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID));
ViewBag.DatumRID = viewList;
And pass "viewList" object to DropDownList helper at razor markup.
Ok. I searched around, and could find anything reasonable to work with. Selectlists don't have a Count() or any() method like most lists. Here's what I came up with:
#{
var counter=0;
foreach(var a in Viewbag.DatumRID)
{
counter++;
break; //stop it so it doesn't iterate through the whole thing since that's unnecessary
}
}
#if(counter>0){//put your dropdown here}
I am attempting to populate a textbox from the value in a separate textbox, ie. using the customer account number to auto-populate the customer name. My AJAX is returning the proper results, however it's not getting populated into the other textbox, which is why I suspect my jQuery is wrong.
<div class="form-group">
#Html.LabelFor(model => model.AccountNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.AccountNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AccountNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CustomerName, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CustomerName, "", new { #class = "text-danger" })
</div>
</div>
[HttpGet]
public ActionResult GetCustomerName(string RecKey)
{
var result = (from c in db.Customers
where c.RecKey.Equals(RecKey)
select new { c.RecName });
return Json(result, JsonRequestBehavior.AllowGet);
}
Returned JSON (only returning one result that's an exact match):
[{"RecName":"This is a customer name"}]
$(document).ready(function () {
var RecKey;
$(function () {
$("#AccountNumber").keydown(function () {
RecKey = $("#AccountNumber").val();
$.ajax({
type: "GET",
url: 'GetCustomerName',
data: { RecKey: RecKey },
success: function (data) {
if (data) {
//alert(data);
$('#CustomerName').val(data.RecName);
}
}
});
});
});
});
I am rather new to jQuery and have had success with autocomplete on the same textbox, however my searching hasn't found much for me to populate other text boxes. Anyone have any ideas?
The issue is because the resulting JSON is an array of objects. If you can guarantee that it will only ever return a single object within that array then you can hard-code the index accessor of the array:
success: function (data) {
if (data) {
$('#CustomerName').val(data[0].RecName);
}
}
Alternatively you can amend your C# code to return a single entity instead of an array:
return Json(result.SingleOrDefault(), JsonRequestBehavior.AllowGet); // or FirstOrDefault()
I think the TextBox helpers only add the name attribute, while your JQuery code is looking for the box by ID....
Try changing;
#Html.TextBoxFor(model => model.CustomerName, new { #class = "form-control" })
to
#Html.TextBoxFor(model => model.CustomerName, new { #class = "form-control", id = "CustomerName" })
You will also need to use either the SingleOrDefault server side or [0] indexer client side as suggested in the other answers - because even though the array only has one item, it is still an array (not an object) so that will need fixed as well.
P.S. A useful tool in debugging stuff like this is pressing F12 to get the developer console up - you can then try typing your jquery code to see if it works directly into the console. As an example if you type $("#CustomerName") do you actually get an object returned? If not - then my answer is the reason why. If so - something else is affecting this.
Simple question, if you use the Html Helper from ASP.NET MVC Framework 1 it is easy to set a default value on a textbox because there is an overload Html.TextBox(string name, object value). When I tried using the Html.TextBoxFor method, my first guess was to try the following which did not work:
<%: Html.TextBoxFor(x => x.Age, new { value = "0"}) %>
Should I just stick with Html.TextBox(string, object) for now?
Try this:
<%= Html.TextBoxFor(x => x.Age, new { #Value = "0"}) %>
note that #Value has a capital V
This should work for MVC3 & MVC4
#Html.TextBoxFor(m => m.Age, new { #Value = "12" })
If you want it to be a hidden field
#Html.TextBoxFor(m => m.Age, new { #Value = "12",#type="hidden" })
It turns out that if you don't specify the Model to the View method within your controller, it doesn't create a object for you with the default values.
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Loads default values
Instructor i = new Instructor();
return View("Create", i);
}
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Does not load default values from instructor
return View("Create");
}
The default value will be the value of your Model.Age property. That's kind of the whole point.
You can simply do :
<%= Html.TextBoxFor(x => x.Age, new { #Value = "0"}) %>
or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :
#Html.TextBoxFor(x => x.Age, new { #Value = (Model==null) ? "0" : Model.Age.ToString() })
This work for me
#Html.TextBoxFor(model => model.Age, htmlAttributes: new { #Value = "" })
value="0" will set defualt value for #Html.TextBoxfor
its case sensitive
"v" should be capital
Below is working example:
#Html.TextBoxFor(m => m.Nights,
new { #min = "1", #max = "10", #type = "number", #id = "Nights", #name = "Nights", Value = "1" })
Here's how I solved it. This works if you also use this for editing.
#Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })
Using #Value is a hack, because it outputs two attributes, e.g.:
<input type="..." Value="foo" value=""/>
You should do this instead:
#Html.TextBox(Html.NameFor(p => p.FirstName).ToString(), "foo")
this worked for me , in this way we setting the default value to empty string
#Html.TextBoxFor(m => m.Id, new { #Value = "" })
If you have a partial page form for both editing and adding, then the trick I use to default value to 0 is to do the following:
#Html.TextBox("Age", Model.Age ?? 0)
That way it will be 0 if unset or the actual age if it exists.
For .net core 5 setting value in htmlAttributes seems doesnt work. But you can use workaround:
var ageTextBox = (TagBuilder) Html.TextBoxFor(x => x.Age);
ageTextBox.Attributes.Remove("value");
ageTextBox.Attributes.Add("value", "value you want to set");
Try this also, that is remove new { } and replace it with string.
<%: Html.TextBoxFor(x => x.Age,"0") %>