mvc 3 view data validation - asp.net-mvc-3

i'm trying to put DropDownList validation to work.
in model:
[Required(ErrorMessage = "this field is required")]
public int ObjectTypeID { get; set; }
in view:
<div class="editor-field">
#Html.DropDownList("ObjectTypeID", string.Empty)
#Html.ValidationMessageFor(model => model.ObjectTypeID)
</div>
if the user leaves the selection empty i expect client side validation to alarm. but this does not happen.
what can be done?

The behavior of system types is that they must have a value when initalized. An integer has a value of "0". Change your model to accept a nullable int:
public int? ObjectTypeID { get; set; }

Just wondering, but why not use DropDownListFor?
For client side validation to work I think you need to turn on ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the web.config for your project, I believe you also need to reference the jquery.validate.unobtrusive.min.js script on your page?

1) You are not loading your dropdownlist
2) Use DropDownListFor in order to match validation with ddl

Related

Required validation on hidden field

I am using client side validation on hidden field in asp.net MVC. I am using required validation using data annotations. I am trying to validate hidden field but it’s not working.
My Model
[Required(ErrorMessage = "From date is required")]
public DateTime? FromDate { get; set; }
My View
#Html.HiddenFor(m => m.FromDate, new { ID = "hfdFromDate" }
#Html.ValidationMessageFor(m => m.FromDate)
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.
As some have pointed the validation isn't performed because the "hidden" property is set.
I had the same issue and ended up using the style tag:
#Html.TextBoxFor(m => m.Foo, new { style = "visibility:hidden"})
The validation is then performed.
Added this line before form.valid().
form.data("validator").settings.ignore = "";
where form is your form element.
In my case :
var form = $("#myForm");

MVC 3 Razor and the display of null dates in forms

I have an MVC 3 website where I display dates in forms using:
<div class="editor-label control-label">
#Html.LabelFor(m => m.rrsfWoman.DateOfBirth)
</div>
<div class="editor-field controls">
#Html.EditorFor(m => m.rrsfWoman.DateOfBirth)
#Html.ValidationMessageFor(m => m.rrsfWoman.DateOfBirth)
</div>
The date of birth is defined in the rrsfWoman class as
public DateTime WomansDateOfBirth { get; set; }
My problem is that as the date of birth field has by default a value of MinDate. Is there a way I can supress the display of the date as 1/01/0001 without making the field nullable.
Thanks
Is there a way I can supress the display of the date as 1/01/0001
without making the field nullable.
The correct way to achieve that is to make the date nullable in your view model. If you don't do that later you will struggle with model binding as well because a non-nullable DateTime field cannot be bound to an empty string and you will have to write custom model binders and stuff to make it work. You will make your life miserable if you don't use view models.
This being said, if you want to go against good practices, you could define a custom editor template for the DateTime type that will perform the check and use an empty value but honestly I don't recommend you doing that:
~/Views/Shared/EditorTemplates/DateTime.cshtml:
#model DateTime
#if (Model == default(DateTime))
{
#Html.TextBox("", "")
}
else
{
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue)
}
You could set the default value of WomansDateOfBirth explicitly like so:
private DateTime _womansDateOfBirth = DateTime.Now;
public DateTime WomansDateOfBirth
{
get { return _womansDateOfBirth; }
set { _womansDateOfBirth = value; }
}
Where DateTime.Now is your MinDate.
If the date field does not allow nulls and you want to force the user to enter a date.
IMO, the best way is to simply clear the input field after the form is built.
So add this little snip-it at the end of your view.
<script type='text/javascript'>
document.getElementById("DateOfBirth").value = "";
</script>

MVC Razor read only TextBoxFor

In a MVC 3 Razor Project, I have defined DisplayFormat in ViewModel to format a DateTime Property
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Posted Date")]
public DateTime PostedDate { get; set; }
And I need to make the field Read Only in View
#Html.TextBoxFor(model => model.PostedDate, new { #readonly = "readonly" })
But when displaying the date in TextBoxFor it does not apply the DisplayFormat. If I Change TextBoxFor to a EditorFor DisplayFormat is applied but can not apply the readonly CSS property.
How to apply the date formatting & make the text box readonly?
you can still use editor for when the editor for renders I believe based on your case it should still render to the text-box after it renders you can use a simple jquery function to add an attribute read-only to the rendered text-box
$("#PostedDate").attr("readonly", "readonly");
not sure if it the best solution but you can try it

MV3 Duplicate Query String Values for CheckBox (true,false for boolean)

I've created a fairly straight forward page with a check box:
#using (Html.BeginForm("MyController", "MyAction", FormMethod.Get))
{
#Html.CheckBoxFor(x => x.MyCheckBox)
<input type="submit" value="Go!" />
}
The URL is populated with the MyCheckBox value twice!? As such:
MyAction?MyCheckBox=true&MyCheckBox=false
It only duplicates the value if the check box is true. If set to false it will only appear once in the query string.
The code above is simplified as I have a couple of drop downs and a textbox on the form which work fine. I don't think there's anything unusual about the code which I've left out from this question.
Has anyone had a similar issue with query string parameters being duplicated?
This behaviour is by design of the checkbox control. The standard HTML checkbox control passes no value if it is not checked. This is unintuitive. Instead, the ASP.Net checkbox control has 2 elements, the standard control which is visible and also a hidden control with a value of 'False'.
Therefore, if the checkbox is not checked, there will be one value passed: False.
If it is checked, there will be two values, True and False. You therefore need to use the following code to check for validity in your code:
bool checkboxChecked = Request.QueryString["MyCheckBox"].Contains("True");
Accepted answer is correct however in my case in a recent development the MVC behaviour is misleading.
The MVC Html.CheckBox(...) and Html.CheckBoxFor(...) generate an extra input of 'type=hidden' with the same ID as the checkbox control, leading to the duplicate URL parameters. I got around this problem by simply including the mark up desired as follows:
#if(checkTrue){
<input type="checkbox" id="MyCheckBox" name="MyCheckbox" checked="checked">
}else{
<input type="checkbox" id="MyCheckBox" name="MyCheckbox">
}
Would be better wrapped upin a helper to use in place of the MVC code so the value check is encapsulated.
As part of my application, the controller maintains sets of query parameters using both form injection and link injection using helpers in order to preserve state (of paging/filtering controls for example) when clicked to navigate within the same controller scope. As a result of this feature, the check box element is always set back to false if the standard MVC helpers are used. It's a good thing I noticed and did not waste much time on this bug.
In my model, I had a collection of checkboxes like so:
public class PrerequisitesViewModel
{
public List<StudentPrerequisiteStatusViewModel> PrerequisiteStatuses { get; set; }
}
public class StudentPrerequisiteStatusViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
In order to get everything to bind correctly, I had to actually convert the values from the querystring and parse them manually with the following code:
// fix for how MVC binds checkboxes... it send "true,false" instead of just true, so we need to just get the true
for (int i = 0; i < model.PrerequisiteStatuses.Count(); i++)
{
model.PrerequisiteStatuses[i].IsSelected = bool.Parse((Request.QueryString[$"PrerequisiteStatuses[{i}].IsSelected"] ?? "false").Split(',')[0]);
}
Alas, it works, but I can't believe this is necessary in MVC! Hopefully, someone else knows of a better solution.
I solve this issue with use #Html.HiddenFor
<input id="checkboxId" type="checkbox" value="true" onchange="changeCheckboxValue()">
#Html.HiddenFor(m => m.MyCheckBox, new { #id = "hiddenId" } )
<script>
function changeCheckboxValue() {
document.getElementById("checkboxId").value = document.getElementById("hiddenId").checked;
}
</script>

Adding profile fields to registration form asp.net mvc3

I am new to mvc and would like to add an additional field to my registration page that is simply a dropdownlist bound to a table in my model (a table of organization names and IDs). However, in my default application I see that the AccountController is using the RegisterModel model to create the register form view. This is fine, I don't want to disturb this. But I want to add a new select box on the page bound to a different model (my model with the organizations). How do I accomplish this?
I've found other posts that suggest I create a wrapper model for both my model and the RegisterModel, but this isn't working. My wrapper model looks like this:
public class RegisterPeopleModel
{
public RegisterModel reg { get; set; }
public fwfEntities fwf { get; set; }
}
And now the field validator for password is no longer working. The code in the view:
<div class="editor-field">
#Html.PasswordFor(m => m.reg.ConfirmPassword)
#Html.ValidationMessageFor(m => m.reg.ConfirmPassword)
</div>
Now renders this:
<div class="editor-field">
<input data-val="true" data-val-equalto="The password and confirmation password do not match." data-val-equalto-other="*.Password" id="reg_ConfirmPassword" name="reg.ConfirmPassword" type="password" />
<span class="field-validation-valid" data-valmsg-for="reg.ConfirmPassword" data-valmsg-replace="true"></span>
</div>
Notice that the IDs of the span and input no longer match. The form no longer works at all. This is leading me to believe I'm taking the wrong approach. Is there a better way of getting my select list on the page bound to a different model?
Thanks in advance.
Is there a better way of getting my select list on the page bound to a
different model?
If the model doesn't meet the requirements of the view you should modify this model. In ASP.NET MVC it is a good practice to design view models and pass only view models to views and not domain models (like for example EF autogenerated classes which is what this fwfEntities type seem to be). So design a view model which contains only the properties needed by your view and have your controller action query the database in order to fetch the model then map the model to a view model and finally pass this view model to the view.
Without seeing RegisterModel my guess is that ConfirmPassword has not got a required attribute for example;
[Required(ErrorMessage = "A password is required")]
public string ConfirmPassword { get; set; }
oh I believe the period in the id is replaced with an underscore so as not to cause issues with Jquery.

Resources