Remove default 0 from numeric textbox - sql

My model has an EditorFor that binds to a not null numeric field in a database. I wish to keep this field blank so that users can enter or scan numbers into the field. Unfortunately, it defaults to a 0. Is there an easy way to remove the 0 while keeping the field not null?
#Html.EditorFor(model => model.RackNumber, new { id = "RackNumber"})

Change model property type to nullable: public int? RackNumber {get;set;}

You can provide the Value attribute like this:
#Html.EditorFor(model => model.RackNumber, new { Value = Model.RackNumber == 0 ? "" : Model.RackNumber.ToString(), id = "RackNumber"})

Related

Assigning Value to Bootstrap-datetimepicker with Format MM/YYYY Displays Incorrect Year

I am using bootstrap-datetimepicker version 4.17.47 in ASP MVC 4 app.
I have this model property:
public DateTime MonthYear { get; set; }
I assign default value in controller (arbitrary value is just an example actual value is determined through some logic):
model.MonthYear = new DateTime(2017, 3, 1);
I display this in view using datepicker so users can update the value as needed:
#Html.TextBoxFor(model => model.MonthYear, new { #class = "form-control input month-picker" })
Script:
$('.month-picker').datetimepicker({
format: 'MM/YYYY',
useCurrent: false,
toolbarPlacement: 'bottom',
viewMode: 'months'
});
The problem is the control displays "03/0001" instead of "03/2017".
What am I missing here?
Apparently the problem is that the input is being filled with a DD/MM/YYYY date from server when datetimepicker is expecting only MM/YYYY. Try formating the textbox, like:
#Html.TextBoxFor(model => model.MonthYear, "{0:MM/yyyy}", new { #class = "form-control input month-picker" })
That should work.

FluentValidation allow null OR specify length?

I have a rule like this:
RuleFor(m => m.Title).Length(1, 75);
However, if the Title is null, I still get the validation stating the Title length must be between 1 and 75 characters, you entered 0.
How can I change the rule so it allows for null title, but if one is specified it must be between 1 and 75 characters? Thanks.
I'm working on a bit of an assumption here, but I'm guessing your title isn't set to null but to string.Empty. You can add particular clauses to any rule by doing the following:
public class Thing
{
public string Title { get; set; }
}
public class ThingValidator : AbstractValidator<Thing>
{
public ThingValidator()
{
this.RuleFor(s => s.Title).Length(1, 75).When(s => !string.IsNullOrEmpty(s.Title));
}
}
As suggested by Yannick Meeus in above post, we need to add 'When' condition to check for not null.
It resolved the issue.
Here I wanted to allow Phone number to be null, but if specified then it should contain ONLY digits.
RuleFor(x => x.PhoneNumber).Must(IsAllDigits).When(x => !string.IsNullOrEmpty(x.AlternateNumber)).WithMessage("PhoneNumber should contain only digits");

How to assign null/string to an int type in MVC Razor using Entity Framework?

I am using a simple MVC 4 application using Entity Framework.
In my View I am displaying data from of a table using webgrid.
View Also has Textboxes(EditorFor) for saving any new record in the table.
I am using partial view for the Textboxes, as in the beginning when the page is launched, the textboxes should remain empty.
Out of 5, two columns are of integer types.
In order to make the textboxes empty initially I am using a new object as -
#if (!dataGrid.HasSelection)
{
Datamodel = new EntityFrDemo.Models.FacultyDetails { DepartmentID = 0, Name = "", Subject = "", YrsExp = 0, Email = "" };
Html.RenderPartial("~/Views/Shared/_FacultyDetails.cshtml", Datamodel);
}
//------------------------------------------------------------------------
#Html.LabelFor(model => model.DepartmentID)
#Html.EditorFor(model => model.DepartmentID)
#Html.ValidationMessageFor(model => model.DepartmentID)
//-----------------------------------------------------------------------------
So I am able to make my boxes empty, however for the Integer type boxes '0' is coming, as I can only assign zero.
So How can I override/superimpose the integer value type boxes to empty string type so that boxes remains empty only in case when no row is selected i.e. in initial stage...?
When you use #Html.EditorFor() with a int value, Razor generate a html tag like this
<input type="number" name="propertyName" id="propertyName" value="propertyValue" />
If you didn't set a value for the int property, the default int value is zero. To set another value in the html tag, you can write it without Razor or you can set the value like the code below.
#Html.EditorFor(model => model.DepartmentID, new { htmlAttributes = new { #Value = "" } })
Note: It is capital "V", not a lower case "v".

Using a list with MVC radiobuttonfor

I am using radiobuttonfor in MVC 4 and I am trying to give the user a selection of items that he can select. My problem is when one of the items is selected and it's posted to the controller, the string value is a .net system.guid rather than the actual guid value.
#foreach (var person in Model.InterviewDates[i].Interviewers) // all interviewers - not filtered
{
var list = Model.InterviewDates[i].Interviewers.Select(p => p.InterviewerID).ToList();
#Html.Raw(person.InterviewerName + " ")
// TODO: Lambda for getting all Chairs based on interview type and interview date
#Html.RadioButtonFor(m => m.InterviewSchedules[i].Chair, list, new { #style = "width:auto;background:none;border:none" })
<br />
}
I have a list of people and it contains their user ids. I then want the user to select a radio button to bind that value to the model.
- list Count = 3 System.Collections.Generic.List<System.Guid>
+ [0] {5fb7097c-335c-4d07-b4fd-000004e2d221} System.Guid
+ [1] {5fb7097c-335c-4d07-b4fd-000004e2d222} System.Guid
+ [2] {5fb7097c-335c-4d07-b4fd-000004e2d223} System.Guid
+ Raw View
When I post it goes here:
[HttpPost]
public ActionResult SubmittedInterviews(InterviewManagement InterviewManagement)
{
return View();
}
This is what I can see in quick watch
- InterviewManagement {IMecheAdmin.Models.InterviewManagement} IMecheAdmin.Models.InterviewManagement
+ InterviewDates Count = 0 System.Collections.Generic.List<IMecheAdmin.Models.InterviewDate>
- InterviewSchedules Count = 1 System.Collections.Generic.List<IMecheAdmin.Models.InterviewSchedule>
- [0] {IMecheAdmin.Models.InterviewSchedule} IMecheAdmin.Models.InterviewSchedule
Chair "System.Collections.Generic.List`1[System.Guid]" string
Cofacilitator null string
Facilitator null string
+ InterviewDate {01/01/0001 00:00:00} System.DateTime
Location null string
Observer null string
Preference false bool
Site null string
+ Raw View
+ InterviewTypes Count = 0 System.Collections.Generic.List<IMecheAdmin.Models.InterviewType>
SelectedMembershipType null string
And this is not what I want:
Chair "System.Collections.Generic.List`1[System.Guid]" string
Doesn't say actual GUID. Any ideas?
Radio button is normally used where we want user to only select only one option from the provided item.
So, you need to pass single object instead of list:
foreach(var item in list)
{
#Html.RadioButtonFor(m => m.InterviewSchedules[i].Chair,
item.InterviewerID,
new { #style = "width:auto;background:none;border:none" })
}

How can I validate a currency field?

I have an ASP.NET MVC-4 application with this currency field:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]
[DataType(DataType.Currency)]
public decimal? Price { get; set; }
This is the corresponding part in my view:
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
If the price is 100 Euro the text field in the view shows:
100,00 €
This is nice.
But I am having problems as soon as I try to do a Postback. The validator pops up and says that the price field needs to be a number.
I can only fix this if (1) I delete the € symbol and (2) replace the decimal separator (replace comma with a dot).
If there is no better solution, I guess I could change the DataFormatString = "{0:F2}" in order to avoid the currency symbol.
But how do I make the validator accept the comma as decimal separator instead of the (American) dot?
Thanks for your help, guys!
So, I was able to solve my problem with jQuery's Globalization plugin from http://github.com/jquery/globalize.
I added the following files to my /scripts folder:
/scripts/globalize.js
/scripts/cultures/globalize.cultures.js
/sctipts/cultures/globalize.culture.de-DE.js
In BundleConfig.cs:
bundles.Add(new ScriptBundle("~/bundles/scripts/globalization").Include(
"~/Scripts/globalize*",
"~/Scripts/cultures/globalize*"));
In _Layout.cshtml:
#Scripts.Render("~/bundles/scripts/globalization")
and in the script section of _Layout.cshtml:
$.validator.methods.number = function (value, element) {
return this.optional(element) || !isNaN(Globalize.parseFloat(value));
}
$.validator.methods.range = function (value, element, param) {
return this.optional(element) || (Globalize.parseFloat(value) >= param[0] && Globalize.parseFloat(value) <= param[1]);
}
However, I couldn't make the currency symbol to work with the client validation, so I also changed the data annotation as follows:
[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]
But that was it. No other changes necessary. I can now enter values like "1,49" or "18,77" and everything gets stored properly in my database.